我的页面中有很多图片,我想隐藏那些高度大于宽度的 。
我尝试了这个简单的代码,但没有用。
HTML
<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。
谢谢
答案 0 :(得分:3)
您忘记了图像数组的索引
window.onload = function() {
var i, img;
var img = document.getElementsByClassName("my_pictures_class");
for (i = 0; i < img.length; i++) {
var width = img[i].clientWidth;
var height = img[i].clientHeight;
if (height > width) {
img[i].style.display = "none";
}
}
};
考虑每个人
const imgList = document.getElementsByClassName("my_pictures_class");
Array.from(imgList).forEach(img => {
const height = img.clientHeight
const width = img.clientWidth
if (height > width) {
img.style.display = "none";
}
})
答案 1 :(得分:1)
您没有提到索引。尽管您可以通过使用querySelectorAll()
和forEach()
来避免使用索引,如下所示:
window.onload = function() {
var imgList = document.querySelectorAll(".my_pictures_class");
imgList.forEach(function(img){
var width = img.clientWidth;
var height = img.clientHeight;
if (height>width){
img.style.display = "none";
}
else{
//Nothing
}
});
};
<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">