gpt4 book ai didi

javascript - 如何增大和减小图像尺寸

转载 作者:行者123 更新时间:2023-11-30 06:24:46 25 4
gpt4 key购买 nike

我有一张图片,宽度设置为 200px,高度设置为 200px。每点击一次图片,图片的宽度和高度应该增加50px,当图片的宽度和高度达到500px时,应该减少50px >,当它将变为 200px 时,它应该再次增加 50px 等等。我该怎么做?

下面的代码对我不起作用:

function Increase_Decrease() {
var w = document.getElementById("img").width;
var h = document.getElementById("img").height;
if (w <= 500 && h <= 500){
var w = document.getElementById("img").width += 50;
var h = document.getElementById("img").height += 50;
} else {
var w = document.getElementById("img").width -= 50;
var h = document.getElementById("img").height -= 50;
}
}

最佳答案

你的问题是你没有跟踪要走哪条路,你只是把它放在中间,你需要在击中任一侧后按下开关才能知道朝哪条路走。

这里我使用state作为开关。

const INCREASE = true
const DECREASE = false

let state = INCREASE

function Increase_Decrease() {
const img = document.getElementById('img')
if (state === INCREASE) {
img.width += 50
img.height += 50
if (img.width >= 500) { state = DECREASE }
} else {
img.width -= 50
img.height -= 50
if (img.width <= 200) { state = INCREASE }
}
}
button {
position: absolute;
}
    <!DOCTYPE html>
<html>
<body>
<button onclick="Increase_Decrease()">Click me</button>
<img id="img" src="https://dummyimage.com/600x400/000/fff" alt="Smiley face" width="42" height="42">

</body>
</html>

关于javascript - 如何增大和减小图像尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51167448/

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