通过他的URL动态定义图像宽度是否真实?

时间:2017-11-13 22:40:17

标签: javascript jquery html css

如何在加载DIV 背景图片属性之前定义图像宽度?

function nn() {
  if (arr !== null) {
    var el = document.getElementById("n");
    var x = Math.floor((Math.random() * 10) + 1);
    var img = new Image();
    img.src = arr[x];
    el.style.width = img.width;
    el.style.backgroundImage = arr[x];
  }
}

$(window).on({
  load: function() {
    resizeBind(width);
    nn(arr);
    return width;
  }
});

arr[]的图片网址很少?

1 个答案:

答案 0 :(得分:-1)

您必须将图片加载到img标记中,等待其load事件,然后才查询图片属性:



var img = document.createElement("img");
img.classList.add("obj");
img.src = "http://www.parisilabs.com/colors2/images/30892183_350_350.jpg";
img.addEventListener('load', function() {
  console.log("Width:%d Height:%d", document.getElementById('test').width,
    document.getElementById('test').height);
}, false);
img.id = "test";
document.getElementById("content").appendChild(img);

<div id="content" />
&#13;
&#13;
&#13;