jQuery - 如果再次单击,则放大单击div并返回原始大小

时间:2016-03-19 18:20:46

标签: javascript jquery jquery-animate

HTML:

<div class="box">
     content
</div>
<div class="box last">
     content
</div>

jQuery的:

$('.box').on('click', function (e) {
    e.preventDefault()
    $(this).stop(true, false).animate({
        width: "+=100",
        height: "+=100",
        top: "-=50",
        left: "-=50"
    }, 300);
    $(this).addClass('zoom')
});

如果在另一个盒子或外面的某个地方(文件正文)发生了点击,我需要将盒子调整回原始状态(大小和位置)。

我尝试过这段代码,但是只要点击其中一个框就会执行代码:

$(document).on('click', ".box.zoom", function () {
    e.preventDefault()
    $(this).stop(true, false).animate({
        width: "-=100",
        height: "-=100",
        top: "+=50",
        left: "+=50"
    }, 300);
    $(this).removeClass('zoom')
});

当前设置位于: https://jsfiddle.net/3ftg4hmc/

3 个答案:

答案 0 :(得分:0)

在点击事件的最后,使用框中的data()方法保存当前位置,然后在下一次点击时恢复上一个位置,如下所示。

$('.box').on('click', function () {
    var position = $(this).data('position'); //get saved position

    if ($(this).hasClass('zoom')) {
        $(this).stop(true, false).animate({
            width: "-=100",
            height: "-=100",
            top: position.top, //use saved position
            left: position.left //use saved position
        }, 300);
        $(this).removeClass('zoom');
    } else {
        $(this).stop(true, false).animate({
            width: "+=100",
            height: "+=100",
            top: "-=50",
            left: "-=50"
        }, 300);
        $(this).addClass('zoom')
    }

    $(this).data('position', $(this).offset());
});

UPDATED FIDDLE

答案 1 :(得分:0)

嗨,我希望这可以帮助你

的Javascript

$('.box').on('click', function (e) {
    e.preventDefault()
    if ($(this).hasClass('zoom')) {
        $(this).stop(true, false).animate({
            width: "-=100",
            height: "-=100",
            top: "+=50",
            left: "+=50"
        }, 300);
        $(this).removeClass('zoom');
    }
    else {
        $(this).stop(true, false).animate({
            width: "+=100",
            height: "+=100",
            top: "-=50",
            left: "-=50"
        }, 300);
        $(this).addClass('zoom');
    }
});

链接https://jsfiddle.net/3ftg4hmc/1/

答案 2 :(得分:0)

$('.box').on('click', function(e) {
  e.preventDefault();
  $(this).stop(true, false).animate({
    width: "+=100",
    height: "+=100",
    top: "-=50",
    left: "-=50"
  }, 300);
  $(this).siblings().attr("style", ""); // new line added
});

只需使用style

就可以清空兄弟div的属性$(this).siblings().attr("style", "");

这是工作小提琴:https://jsfiddle.net/3ftg4hmc/3/