0

我正在编写一个响应式程序,它不断改变某些元素的宽度,对应于其他具有 % 宽度的元素。哪个工作正常。但是当我想将 div 中的所有图像更改为与图像的祖父母一样大时,我遇到了一个问题。

JS:

var thebigone = document.getElementById('imgpresentation');
var demimages = document.getElementsByClassName('presentatinthis');

fixtheresponsiveness = setInterval(fixthis,1000);
function fixthis()
{
    demimages.style.width = thebigone.offsetWidth+"px";
}

fixtheresponsiveness();

HTML:

<div id="imgpresentation" class="imgpresentation">
    <div id="slidethemimgpresentation" class="slidethemimgpresentation">
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg1.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg2.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg3.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg4.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg5.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg6.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg7.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg8.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg9.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg10.jpg"/>
    </div>
</div>

如果我用“id”替换“class”,用“getelementbyid”替换“getelementsbyclassname”,它会起作用,但它只适用于div内的第一个img。

我不想使用 jQuery,所以请不要建议 $('.presentatinthis')

4

1 回答 1

2

document.getElementsByClassName返回一个NodeList这意味着您必须遍历结果才能访问和设置每个节点的 style

var i = demimages.length;
while (i--) demimages[i].style.width = thebigone.offsetWidth+"px";
于 2013-08-10T12:23:17.183 回答