如何在加载图像作为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[]
在哪里有很少的图像 URL?
您必须将图像加载到 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" />