Получить размер фонового изображения CSS с помощью JavaScript? - PullRequest
38 голосов
/ 23 июня 2010

Можно ли использовать JavaScript для получения фактического размера (ширины и высоты в пикселях) фонового изображения, на которое ссылается CSS?

Ответы [ 5 ]

50 голосов
/ 23 июня 2010

Да, и я бы сделал это так ...

  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;

    var width = image.width,
        height = image.height;

    alert('width =' + width + ', height = ' + height)    

}

Некоторые заметки ...

  • Нам нужно удалить часть url() этого JavaScriptвозвращается, чтобы получить правильный источник изображения.Нам нужно разделить на , в случае, если элемент имеет несколько фоновых изображений.
  • Мы создаем новый Image объект и устанавливаем его src для нового изображения.
  • Мы можемзатем прочитайте ширину и высоту.

jQuery, вероятно, будет гораздо меньше головной боли, чтобы начать работу.

13 голосов
/ 17 июля 2012

Нельзя комментировать под ответами, поэтому вот версия jQuery, включающая background-size (опубликована, потому что этот вопрос является первым в поиске Google и может быть полезен кому-то, кроме меня):

function getBackgroundSize(selector, callback) {
  var img = new Image(),
      // here we will place image's width and height
      width, height,
      // here we get the size of the background and split it to array
      backgroundSize = $(selector).css('background-size').split(' ');

  // checking if width was set to pixel value
  if (/px/.test(backgroundSize[0])) width = parseInt(backgroundSize[0]);
  // checking if width was set to percent value
  if (/%/.test(backgroundSize[0])) width = $(selector).parent().width() * (parseInt(backgroundSize[0]) / 100);
  // checking if height was set to pixel value
  if (/px/.test(backgroundSize[1])) height = parseInt(backgroundSize[1]);
  // checking if height was set to percent value
  if (/%/.test(backgroundSize[1])) height = $(selector).parent().height() * (parseInt(backgroundSize[0]) / 100);

  img.onload = function () {
    // check if width was set earlier, if not then set it now
    if (typeof width == 'undefined') width = this.width;
    // do the same with height
    if (typeof height == 'undefined') height = this.height;
    // call the callback
    callback({ width: width, height: height });
  }
  // extract image source from css using one, simple regex
  // src should be set AFTER onload handler
  img.src = $(selector).css('background-image').replace(/url\(['"]*(.*?)['"]*\)/g, '$1');
}

или как плагин jQuery:

(function ($) {
// for better performance, define regexes once, before the code
var pxRegex = /px/, percentRegex = /%/, urlRegex = /url\(['"]*(.*?)['"]*\)/g;
$.fn.getBackgroundSize = function (callback) {
  var img = new Image(), width, height, backgroundSize = this.css('background-size').split(' ');

  if (pxRegex.test(backgroundSize[0])) width = parseInt(backgroundSize[0]);
  if (percentRegex.test(backgroundSize[0])) width = this.parent().width() * (parseInt(backgroundSize[0]) / 100);
  if (pxRegex.test(backgroundSize[1])) height = parseInt(backgroundSize[1]);
  if (percentRegex.test(backgroundSize[1])) height = this.parent().height() * (parseInt(backgroundSize[0]) / 100);
  // additional performance boost, if width and height was set just call the callback and return
  if ((typeof width != 'undefined') && (typeof height != 'undefined')) {
    callback({ width: width, height: height });
    return this;
  }
  img.onload = function () {
    if (typeof width == 'undefined') width = this.width;
    if (typeof height == 'undefined') height = this.height;
    callback({ width: width, height: height });
  }
  img.src = this.css('background-image').replace(urlRegex, '$1');
  return this;
}
})(jQuery);
6 голосов
/ 06 марта 2012
var actualImage = new Image();
actualImage.src = $('YOUR SELECTOR HERE').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");

actualImage.onload = function() {
    width = this.width;
    height = this.height;
}
5 голосов
/ 12 июля 2013
var dimension, image;

image = new Image();
image.src = {url/data}
image.onload = function() {
    dimension = {
        width: image.naturalWidth,
        height: image.naturalHeight
    };
    console.log(dimension); // Actual image dimension
};
1 голос
/ 23 июня 2010

Вот оно в jQuery:

var actualImage = new Image();
actualImage.src = $('YOUR SELECTOR HERE').css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");

actualImage.width // The actual image width
actualImage.height // The actual image height

Спасибо за сладкое регулярное выражение alex.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...