简体   繁体   中英

jQuery Shake broke position:fixed

In a web site I want to shake a div which includes an image, it is fixed at the bottom of the page. I try to add shake function to it, it is shaking but position changes to left side. How can I fix it ? Let me write the code.

     var css_shake={
     right: '225px',
     left: 'auto',
     position: 'fixed',
     bottom:'50px'
 }
  jQuery.fn.shake = function() {
  this.each(function(i) {
  jQuery(this).css(css_shake);
    for (var x = 1; x <= 3; x++) {
        jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50);
    }
});
return this;
}

when write $(div).shake() it works but not I want to do.

 <div  id="affix_sepet">
    <img src="img/sepet_yeni.png" height="226" width="163">
 </div>

This div also have bootstrap affix : jQuery("#affix_sepet").affix()

     var css_shake={
     right: '225px',
     left: 'auto',
     position: 'fixed',
     bottom:'50px'
 }
  jQuery.fn.shake = function() {
  this.each(function(i) {
  jQuery(this).css(css_shake);

        jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50);
        jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50);
        jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50);
        jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50);
        jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50);
        jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50);




});
return this;
}

You are using absolute left values for your animation rather than relative values. Try using this syntax:

jQuery(this).animate({ left : '+=25px' }, 10).animate({ left : '-=25px' }, 10) ;

currently you are bouncing the element around absolute position -25 to 25, and leaving it up against the left border.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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