猿问

如果图像的高度大于宽度,则隐藏图像

我的页面中有很多图片,我想隐藏那些高度大于宽度的图片。我尝试使用这个简单的代码,但它不起作用。


超文本标记语言


<img src="/path/img_1" class="my_pictures_class">

<img src="/path/img_2" class="my_pictures_class">

<img src="/path/img_3" class="my_pictures_class">

<img src="/path/img_4" class="my_pictures_class">

<img src="/path/img_5" class="my_pictures_class">

...


JS


window.onload = function() {

   var i, img;

   var img = document.getElementsByClassName("my_pictures_class"); 

   for (i = 0; i < img.length; i++) {

     var width = img.clientWidth;

     var height = img.clientHeight;

     if (height>width){

       img[i].style.display = "none";

     }

     else{

        //Nothing

     }

   }

};



我无法使用 Jquery。


潇潇雨雨
浏览 102回答 2
2回答

扬帆大鱼

您忘记了图像数组的索引window.onload = function() {&nbsp; var i, img;&nbsp; var img = document.getElementsByClassName("my_pictures_class");&nbsp; for (i = 0; i < img.length; i++) {&nbsp; &nbsp; var width = img[i].clientWidth;&nbsp; &nbsp; var height = img[i].clientHeight;&nbsp; &nbsp; if (height > width) {&nbsp; &nbsp; &nbsp; img[i].style.display = "none";&nbsp; &nbsp; }&nbsp; }};考虑每个const imgList = document.getElementsByClassName("my_pictures_class");Array.from(imgList).forEach(img => {&nbsp; const height = img.clientHeight&nbsp; const width = img.clientWidth&nbsp; if (height > width) {&nbsp; &nbsp; img.style.display = "none";&nbsp; }})

梦里花落0921

您错过了提及索引。尽管您可以通过使用querySelectorAll()and来避免使用索引forEach(),如下所示:window.onload = function() {&nbsp; &nbsp;var imgList = document.querySelectorAll(".my_pictures_class");&nbsp; &nbsp;imgList.forEach(function(img){&nbsp; &nbsp; &nbsp;var width = img.clientWidth;&nbsp; &nbsp; &nbsp;var height = img.clientHeight;&nbsp; &nbsp; &nbsp;if (height>width){&nbsp; &nbsp; &nbsp; &nbsp;img.style.display = "none";&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;else{&nbsp; &nbsp; &nbsp; &nbsp; //Nothing&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;});};<img src="https://homepages.cae.wisc.edu/~ece533/images/cat.png" class="my_pictures_class"><img src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png" class="my_pictures_class"><img src="https://homepages.cae.wisc.edu/~ece533/images/arctichare.png" class="my_pictures_class"><img src="https://homepages.cae.wisc.edu/~ece533/images/serrano.png" class="my_pictures_class"><img src="https://homepages.cae.wisc.edu/~ece533/images/boat.png" class="my_pictures_class">
随时随地看视频慕课网APP

相关分类

Html5
我要回答