如何在加载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[]
的图片网址很少?
答案 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;