Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

Get the Size of a CSS Background Image Using JavaScript?

Is it possible to use JavaScript to get the actual size (width and height in pixels) of a CSS referenced background image?

question from:https://stackoverflow.com/questions/3098404/get-the-size-of-a-css-background-image-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes, and I'd do it like this...

window.onload = function () {
  var imageSrc = document
    .getElementById('hello')
    .style.backgroundImage.replace(/url((['"])?(.*?)1)/gi, '$2')
    .split(',')[0];

  // I just broke it up on newlines for readability

  var image = new Image();
  image.src = imageSrc;

  image.onload = function () {
    var width = image.width,
      height = image.height;
    alert('width =' + width + ', height = ' + height);
  };
};

Some notes...

  • We need to remove the url() part that JavaScript returns to get the proper image source. We need to split on , in case the element has multiple background images.
  • We make a new Image object and set its src to the new image.
  • We can then read the width & height.

jQuery would probably a lot less of a headache to get going.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...