我试图让这段代码在上半部分后停止,然后当你再次点击时它缩小了。所以,点击2次。
我将如何实现这一目标?
$('#container').click(function () {
$(this).animate({
'width': '400px',
'height': '400px',
'left': '90px',
'top': '90px'
}, 200);
$(this).animate({
'width': '200px',
'height': '200px',
'left': '90px',
'top': '90px'
}, 200);
});
我在Stack Overflow上查看了与此相关的所有问题,但没有一个允许您点击已调整大小的项目。
答案 0 :(得分:1)
您需要在元素上使用data属性来存储元素的状态。像这样
$('#container').click(function () {
if ($('#container').data('state') === '0') { //check the state
$(this).animate({
'width': '400px',
'height': '400px',
'left': '90px',
'top': '90px'
}, 200);
$('#container').data('state', '1'); //store the state on the element
} else {
$(this).animate({
'width': '200px',
'height': '200px',
'left': '90px',
'top': '90px'
}, 200);
$('#container').data('state', '0'); //store the state on the element
}
});
http://jsfiddle.net/mmk2c4vn/5/
但是如果你使用这个很多时间你需要使用类选择器而不是ID&#39>
$('.container').click(function () {
if ($(this).data('state') === '0') {
$(this).animate({
'width': '400px',
'height': '400px',
'left': '90px',
'top': '90px'
}, 200);
$(this).data('state', '1');
} else {
$(this).animate({
'width': '200px',
'height': '200px',
'left': '90px',
'top': '90px'
}, 200);
$(this).data('state', '0');
}
});
http://jsfiddle.net/mmk2c4vn/13/
在你的元素上存储一些状态比暴露一个全局变量要好得多,这就是为什么我不建议你创建另一个变量只是为了切换而你可以使用国家供参考。
如果$('#container').data('state')
不起作用,您可以使用$('#container').attr('data-state')
答案 1 :(得分:1)
如果您只想要切换效果,可以通过几种不同的方式实现此目的。
第一种方法是跟踪"状态"应用程序中的图像。
var enlarged = false;
$('#container').click(function () {
$(this).stop(true, false).animate({
width: enlarged ? 200 : 400,
height: enlarged ? 200 : 400,
left: 90,
top: 90
}, 200);
enlarged = !enlarged;
});
http://jsfiddle.net/mmk2c4vn/4/
第二种方法是写入数据缓存并以这种方式跟踪图像状态。
$('#container').click(function () {
var _this = $(this),
enlarged = _this.data('enlarged') || 0;
_this.stop(true, false).animate({
width: enlarged ? 200 : 400,
height: enlarged ? 200 : 400,
left: 90,
top: 90
}, 200);
_this.data({ enlarged: !enlarged });
});
http://jsfiddle.net/mmk2c4vn/6/
当然,这只是众多方法中的两种。
答案 2 :(得分:0)
试试这个:
var clicks = 0;
$('#container').click(function () {
clicks++;
if (clicks % 2 !== 0) {
$(this).animate({
'width': '400px',
'height': '400px',
'left': '90px',
'top': '90px'
}, 200);
} else {
$(this).animate({
'width': '200px',
'height': '200px',
'left': '90px',
'top': '90px'
}, 200);
}
});