如何在点击时反复增加CSS属性的值?

时间:2016-07-11 16:22:26

标签: javascript jquery css margin

我想在每次点击不同的元素时添加(在这种情况下,从技术上减少)元素的值。到目前为止我所拥有的:

$("#trigger_heritage").click(function () {
  $(".heritage_content ul").css("margin-left", + -880);
  // So each time clicking shall move the .heritage_content ul-element 880px further left
});

最左边880px,但只有一次。我想要的是每次点击其他元素时这个值都会增加。

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以使用-=[value]格式提供css()格式的字符串,您可以使用该字符串修改当前值。试试这个:

$("#trigger_heritage").click(function () {
    $(".heritage_content ul").css("margin-left", '-=880');
});

Working example

答案 1 :(得分:1)

设置一个变量,比如$marginLeft,每次调用函数时都增加它,然后设置margin-left:$marginLeft ....

答案 2 :(得分:1)

这是一个简单的例子:

$(document).ready(function() {
    var move = 0;
    $(".left").click(function () {
        move -= 25;
        $(".move").css("margin-left", move + "px");
    });
    $(".right").click(function () {
        move += 25;
        $(".move").css("margin-left", move + "px");
    });
})

小提琴:https://jsfiddle.net/gjfjahjo/