我正在编写一个响应式程序,它不断更改某些元素的宽度,对应于具有基于%宽度的其他元素。哪个工作正常。但是当我想要将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>
如果我将“class”替换为“id”,将“getelementsbyclassname”替换为“getelementbyid”,那么它只适用于div中的第一个img。
我不想使用jQuery,所以请不要建议$('。presentatinthis')
答案 0 :(得分:2)
document.getElementsByClassName
会返回NodeList,,这意味着您必须遍历结果才能访问并设置每个节点 style
var i = demimages.length;
while (i--) demimages[i].style.width = thebigone.offsetWidth+"px";