简体   繁体   English

如何使用javascript定位所有类。 没有jQuery

[英]How to target all classes with javascript. No jQuery

I am writing a responsive program that keeps changing the width of sertain elements, corresponding to other elements which have a % based width. 我正在编写一个响应式程序,它不断改变某些元素的宽度,对应于其他具有%宽度的元素。 Which works fine. 哪个工作正常。 But i ran into a problem when i wanted to change all images in side a div to be as big as the grand parent of the images. 但是当我想要将div中的所有图像更改为与图像的大父母一样大时,我遇到了一个问题。

JS: 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: 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>

It works if i replace "class" with "id" and "getelementsbyclassname" with "getelementbyid" but then it only works on the first img inside the div. 如果我将“class”替换为“id”和“getelementsbyclassname”替换为“getelementbyid”,但它只适用于div中的第一个img。

I do not wish to use jQuery, so please do not suggest $('.presentatinthis') 我不想使用jQuery,所以请不要建议$('。presentatinthis')

document.getElementsByClassName returns a NodeList , which means you would have to loop over the result to access and set each Node's style document.getElementsByClassName返回一个NodeList这意味着你必须遍历结果才能访问并设置每个Node的 style

var i = demimages.length;
while (i--) demimages[i].style.width = thebigone.offsetWidth+"px";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM