我有一张图像,其宽度设置为200px
,高度设置为200px
。对于图片的每次点击,其宽度和高度应增加50px
,当宽度和高度达到500px
时,其宽度应随着50px
减小,并且当其变为{{ 1}},它也应该随着200px
的增加而增加,依此类推。我该怎么办?
以下代码对我不起作用:
50px
答案 0 :(得分:1)
您需要存储缩放状态-用户当前是否正在放大或缩小,并根据您指定的范围更改缩放状态
const $image = document.querySelector('#image');
const delta = 50;
let zoom = +1;
$image.onclick = function() {
const height = $image.getBoundingClientRect().height; // or $image.height
if (height >= 500) {
zoom = -1;
} else if (height <= 200) {
zoom = +1;
}
$image.height += zoom * delta;
}
<img src="https://media1.tenor.com/images/9f8deeccdee39a5ed36a0a7ecfa3a1a8/tenor.gif?itemid=10044706" height="200" id="image" />
此外,请记住,不需要缩放图像的宽度和高度。缩放宽度会自动缩放高度,反之亦然,以保持<宽高比。
答案 1 :(得分:1)
您的问题是,您没有跟踪要走的路,只是将其保持在中间,一旦碰到任一侧就需要翻开开关以知道要走的路。
在这里,我使用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>
答案 2 :(得分:-1)
尝试这个。
var onIncrease = true;
function IncDec() {
var x = document.getElementById("myImg");
if (onIncrease) {
x.width += 50;
x.height += 50;
} else {
x.width -= 50;
x.height -= 50;
}
if (x.width == 500)
onIncrease = false;
if (x.width == 200)
onIncrease = true;
console.log("width: ", x.width, "height: ", x.height);
}
<!DOCTYPE html>
<html>
<body>
<img id="myImg" onclick="IncDec()" src="https://vignette.wikia.nocookie.net/simpsons/images/0/01/200px-Langdon_Alger.png/revision/latest?cb=20120815160236" alt="The Pulpit Rock" width="200" height="200">
</body>
</html>
答案 3 :(得分:-1)
尝试这个。我希望这能帮到您。无需设置高度,因为高度会根据宽度自动调整。
<html>
<head>
<script>
var zoomIn = true, zoomOut = false;
function Increase_Decrease(){
var w = document.getElementById("img").width;
var h = document.getElementById("img").height;
if(w == 500) {
zoomIn = false;
zoomOut = true;
}
else if(w == 200) {
zoomIn = true;
zoomOut = false;
}
if(zoomIn && w <= 500) {
var w1 = document.getElementById("img").width = w + 50;
}
else if(zoomOut && w > 200) {
var w1 = document.getElementById("img").width = w - 50;
}
console.log(w,h);
}
</script>
</head>
<body>
<div>
<img id="img" onclick="Increase_Decrease()" src="https://placeimg.com/200/200/animals" alt="img">
</div>
</body>
</html>