gpt4 book ai didi

javascript - 为什么我不能使用此功能更改图像的宽度?

转载 作者:行者123 更新时间:2023-11-29 22:21:38 24 4
gpt4 key购买 nike

只有当图像宽度大于 200px 时,我才尝试将图像的宽度更改为 200px(固定大小),否则我想保留其原始宽度。

现在下面的代码可以工作了:

<img src="../images/browse-files.png"  style="width:200px" onload="var img = new Image(); img.src = this.src; if(img.width <= 680){ var imgW= '680' + 'px' ; this.style.width =imgW;} "/>

但下面的代码没有:

<script type="text/javascript">
resize(){
var img = new Image();
img.src = this.src;
if(img.width <= 680){
var imgW= '680' + 'px' ;
this.style.width = imgW;
}
return this.style.width;
}
</script>

<img src="../images/browse-files.png" style="width:200px" onload="return resize() "/>

我想知道我用最后一种方法做错了什么。我更喜欢最后一个方法,因为我想在一个 .js 页面上包含所有 JavaScript 函数。

非常感谢。

最佳答案

您没有正确声明函数。

function resize(){
var img = new Image();
img.src = this.src;
if(img.width <= 680){
...
}
}

关于javascript - 为什么我不能使用此功能更改图像的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12123981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com