Javascript:点击后如何增加和减少图像 [英] Javascript: how to increase and decrease image after clicking on it

查看:89
本文介绍了Javascript:点击后如何增加和减少图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图像宽度= 200,高度= 200。我需要在每次点击图像后,图像增加50px,当它变为500px时,它必须减少50px,当它变为200px时,它必须再增加50px,依此类推。

我该怎么办?



我尝试过:



我试过这样但是错了。



I have image Width=200, Height=200. I need after every click on image, that image increase with 50px, and when it will become 500px, it must decrease with 50px, and when it will become 200px, again it must increase with 50px and so on.
How can i do it?

What I have tried:

I have tried like this but it's wrong.

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;
    }
}

推荐答案

改进版

an improved version
<pre>var increasing=1;
var min_width=200;
var change=50;
var max_lenght=500;
function Increase_Decrease() {

	document.getElementById("img").width += change*increasing;
	document.getElementById("img").height += change*increasing;
	if(document.getElementById("img").width >= max_lenght) {
		increasing=-1;
	} else if(document.getElementById("img").width <= min_width) {
		increasing=1;
	}
}


您的代码将执行的操作是调整大小200 - > 250 - > 300 - > 350 - > 400 - > 450 - > 500 - > 450按预期,但在此之后,尺寸小于500,因此它将再次增加。它会振荡500 - > 450 - > 500 - > 450 - > 500 - > 450等等

您需要记住您是处于上升阶段还是处于下降阶段。最简单的方法(其他人可能不同意)是向图像标记添加属性。例如



What your code will do is resize 200 -> 250 -> 300 -> 350 -> 400 -> 450 -> 500 -> 450 as intended, but after that, the size is less than 500, so it will increase again. It will oscillate 500 -> 450 -> 500 -> 450 -> 500 -> 450, etc.
You need to remember whether you are in a going up or a going down phase. The simplest way (other folks may disagree) is to add an attribute to the image tag. e.g.

function Increase_Decrease() {
    var img = document.getElementById("img");
    var w = img.width;
    var h = img.height;

    if (w <= 200 && h <= 200) {
       img.changeSize = 50;   // At bottom of range. So must now go up
    } else if (w >= 500 && h >= 500) {
       img.changeSize = -50;    // At top of range. So must now go down again
    }

    img.width += 1 * img.changeSize;   // Attributes are strings. Multiply by 1 is one of several ways to quickly convert it to a number
    img.height += 1 * img.changeSize;
}





这一切都来自我的头脑。它完全没有经过测试。



This is all from the top of my head. It is totally untested.


这篇关于Javascript:点击后如何增加和减少图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆