I want to move button left-right and right-left using jquery

前端 未结 5 1335
执笔经年
执笔经年 2021-01-24 06:11

I am able to move button to left side but after that how i can again move it to right side. Can i also use delay here.

Here is the code that i have tried:



        
相关标签:
5条回答
  • 2021-01-24 06:44

    Do execly the same only to the right, Its not that hard if you can make it go left.

    0 讨论(0)
  • 2021-01-24 06:48

    Yes, the animate function takes a function that is called after the animation is complete. So you can do:

     $(document).ready(function () {
          example_animate(100);
      });
    
      function example_animate(px) {   
         $('#Button1').animate({
             'marginLeft': px
         }, function(){
           $('#Button1').animate({
             'marginLeft': 1
           });
         });
     }
    

    http://jsbin.com/ixajol/1/edit

    0 讨论(0)
  • 2021-01-24 06:52

    Maybe

    var button_init_marginLeft;
    $(document).ready(function () {
       button_init_marginLeft = $('#Button1').css("marginLeft");
       example_animate(10, true);
       example_animate(null, false);
    });
    
    function example_animate(px, to_left) {
      if (to_left)
      {
        $('#Button1').animate({
          'marginLeft': px
        });
      }
      else
      {
        $('#Button1').animate({
          'marginLeft': button_init_marginLeft
        });
      }
    }
    

    ?

    0 讨论(0)
  • 2021-01-24 07:01

    Cannot answer properly without looking at your HTML and CSS but what you are doing is right. Simply call your example_animate() with a negative value

    i.e.

    example_animate(-10);
    

    Or if you want to bring it to the original value (assuming originally it had 0 margin)

    example_animate(0);
    

    Note: This is probably not the best way to animate

    0 讨论(0)
  • 2021-01-24 07:03

    you can use this, it is working perfectly for me, it will continuously move your element back and forth, and you can also vary animation speed.

    function animatethis(targetElement, speed) {
            $(targetElement).animate({ marginLeft: "+=10px" },
    {
        duration: speed,
        complete: function () {
            targetElement.animate({ marginLeft: "-=10px" },
            {
                duration: speed,
                complete: function () {
                    animatethis(targetElement, speed);
                }
            });
        }
    )};
    }
    

    use this to implement:

    animatethis($('#controlid'), 1500);
    
    0 讨论(0)
提交回复
热议问题