简体   繁体   English

每次单击将元素向左移动

[英]Move an element left on each click

I think My main question is "how do I write this?" 我想我的主要问题是“我怎么写?” Its a simple thing. 这很简单。 for every click the css left property gets 500px taken off. 每单击一次,css left属性将被取消500px。 (moved 500px to the left) (向左移动500px)

I am having a hard time with the variables and just ... I don't know. 我在使用变量时遇到困难,只是...我不知道。

$(document).ready(function() { 

    var belt-move = 500;
    var belt-ammount = $(".belt").css('left');
    belt-move -=  belt-ammount;


     $(".next").click(function() {
        $(".belt").animate(belt-move, 500, "swing");
     });
}); 

First of all JavaScript (ECMAScript) doesn't allow minus character '-' in variables names, so you can't use the name belt-move , instead you should use underscore '_' ( belt_move ) or camel case convention ( beltMove ). 首先,JavaScript(ECMAScript)不允许在变量名称中使用减号'-',因此您不能使用名称belt-move ,而应使用下划线'_'( belt_move )或驼峰大小写约定( beltMove ) 。

Second: Defining jQuery animation you need to define what property you want to change, in this case 'left'.The 'swing' easing function is default so you don't need to pass it. 第二:定义jQuery动画时,您需要定义要更改的属性,在本例中为'left'。'swing'缓动函数是默认设置,因此您无需传递它。

Third: $(function() {...}); 第三: $(function() {...}); is shorter version of $(document).ready(function() {...}); $(document).ready(function() {...});较短版本$(document).ready(function() {...});

So the final code should look like this: 因此,最终代码应如下所示:

$(function() {
    var beltMove = 500;
    var moveDuration = 500;
    $(".next").click(function() {
        var jqBelt = $(".belt");
        jqBelt.animate({left:"-="+beltMove}, moveDuration);
    });
});

try this..... 尝试这个.....

$(document).ready(function() { 

    var belt-move = 500;
     $(".next").click(function() {
         var belt-ammount = parseInt($(".belt").css('left'));
          belt-move =  belt-ammount-belt-move;
        $(".belt").animate(belt-move, 500, "swing");
     });
}); 

Change this line: var belt-ammount = $(".belt").css('left'); 更改此行: var belt-ammount = $(".belt").css('left'); to var belt-ammount = parseInt($(".belt").css('left')); var belt-ammount = parseInt($(".belt").css('left')); . The reason is that .css will return with px at the end of the pixel, eg `500px'. 原因是.css将以px末尾的px返回,例如“ 500px”。

You don't need to parse out the left property or do the subtracting yourself - the animate function has this capability built in: 您不需要解析出left属性,也不需要自己减去animate函数内置了以下功能:

 $(".next").click(function() {
    $(".belt").animate('-=500px', 500, "swing");
 });

See http://www.jsfiddle.net/ExRR7/ for a simple demo of this 有关此内容的简单演示,请参见http://www.jsfiddle.net/ExRR7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM