需要帮助使用Javascript调整图像大小

时间:2018-04-13 01:15:03

标签: javascript html html5

我正在构建一个小脚本,根据原始大小调整HTML页面上的图像大小。例如,如果图像A的宽度大于35像素,则将该图像的大小调整为35像素宽,否则不执行任何操作。然而经过一天的搜索和许多失败的尝试后,我仍然不知道我哪里出错了。非常感谢任何帮助。

我正在调整大小的图像没有ID,我没有能力将ID添加到他们身上。以下是我目前的脚本。

更新:这是我的当前代码

        <!-- DYNAMIC FORMAT SCRIPT -->
<script>
function dynamicFormat() {
 var allImg = document.querySelectorAll('img')
  allImg.forEach(function(img) {
    const widthStr = img.style.width;
    const widthNum = Number(widthStr.slice(0, widthStr.length - 2));
    if (widthNum >= 35) img.style.width = '35px';
    // other changes if desired
  });
} 
</script>
<!-- DYNAMIC FORMAT SCRIPT -->

1 个答案:

答案 0 :(得分:0)

在完全加载后检索图像宽度会更加可靠,因为实际宽度有时会与通过img.style.width设置的宽度不同。

for(let img of document.querySelectorAll('img')) {
  img.onload = () => {
    let widthNum = img.width; // this should already be a number.
    if (widthNum >= 35) img.style.width = '35px';
  };
}
相关问题