如何使用JS设置img属性



我们有一个有很多图片的页面,它们没有宽度和高度attr,所以我的任务将为页面上的所有图片设置这个attr

const images = document.querySelectorAll(" img ")

然后使用foreach我需要设置attr

也许这个答案对你的问题有帮助

const images = document.querySelectorAll('img');
images.forEach((img) => {
// to get attribute width & height of img 
let img_width  = img.getAttribute('width');
let img_height = img.getAttribute('height');
// to set attribute width & height of img
img.width  = '100px';
img.height = '100px';
// or to set attribute width & height you can set using style attribute
img.style.width  = '100px';
img.style.height = '100px';
})

最新更新