嗨,伙计们,我正在处理一个问题,获取存储在DOM中的多张图片宽度。
我的html看起来像:
<div id="showcase" class="showcase">
<div class="showcase-slide">
<div class="showcase-content">
<img src="https://asp.zone-secure.net/v2/90/10158/58365/multimedia/1_1/1.jpg" alt="02" />
</div>
</div>
<div class="showcase-slide">
<div class="showcase-content">
<img src="https://asp.zone-secure.net/v2/90/10158/58365/multimedia/1_1/2.jpg" alt="02" />
</div>
</div>
<div class="showcase-slide">
<div class="showcase-content">
<img src="https://asp.zone-secure.net/v2/90/10158/58365/multimedia/1_1/3.jpg" alt="02" />
</div>
</div>
<div class="showcase-slide">
<div class="showcase-content">
<img src="https://asp.zone-secure.net/v2/90/10158/58365/multimedia/1_1/4.jpg" alt="02" />
</div>
</div>我尝试过的:
for(var i=0; i < mineContor; i++){
var img = $("img")[i];
console.log(img.width);
}规格: mineContor =4(我有多少个imgs );
发行:
240
(3) 0有时就像上面的控制台,其中240 px宽度是第一张图片的真实宽度。有时就像咆哮。
(4) 0即使console.log(img.src);用正确的src路径返回DOM中的4幅图像!此外,这些图像有不同的尺寸。
问题:
为什么是0而不是宽度?
发布于 2015-07-16 12:33:26
用$(window).load(function(){});编写代码
这是因为它在加载所有其他东西(如图像)时也会执行。
所以你的代码变成:
$(window).load(function() {
for(var i=0; i < mineContor; i++){
var img = $("img")[i];
console.log(img.width);
}
});发布于 2015-07-16 12:34:00
$("img").each(function(){
console.log($(this).css("width"));
OR
console.log($(this).width());
});发布于 2015-07-16 12:42:38
我不喜欢你的变量mineContor的想法。这似乎不是一个非常灵活的解决方案。我建议一种不使用jQuery或任何外部库的替代解决方案:
// get all images (img) on the page
var images = document.getElementsByTagName('img');
// iterate over the images and return the width for every single image
for (var i = 0; i < images.length; i++) {
console.log((i + 1) + '. image has width ' + images[i].width + 'px');
}这比硬编码变量中的图像数量更好、更灵活。
编辑:
上面的代码最初只是作为对其他答案的补充,作为不使用jQuery的替代方法,并且避免对变量mineContor进行硬编码。
只有在DOM完全加载之后,文档中的图像才能被读取。
https://developer.mozilla.org/en/docs/Web/API/GlobalEventHandlers/onload
下面是一个扩展,展示了如何在页面上实现代码示例:
var getImageWidth = function() {
// declare all variables in the beginning
var images, i;
// get all images, it returns an HTMLCollection, an array-like object
images = document.getElementsByTagName('img');
// iterate over the images and get the width for every one of them
console.log((i + 1) + '. image has width ' + images[i].width + 'px');
}
// execute the function after the page has finished loading
// important: no brackets after the function
window.onload = getImageWidth;根据您的需要调整函数的主体,方法是用console.log重新安排输出,或者返回值(可能是数组)。
https://stackoverflow.com/questions/31454145
复制相似问题