简体   繁体   中英

jQuery animate to top of the viewport

I'm creating a product page for an e-commerce website which has a fixed bar at the top of the page and the basket within that. There are lots of items on the page and hence there are lots of 'Add To Basket' buttons.

I need the Add To Basket button to fly up to the basket at the fixed bar. At the moment, I've managed to get the box to appear where I need it to appear when clicked, however there isn't any transition with the animation. I'm guessing it could be the fact that I'm turning the object into a position:fixed; .

Here's a fiddle of what I've got so far.. Hope you can help!

http://jsfiddle.net/d7tHU/

$('.addToCart').click(function(){
    $(this).css('position','fixed');
    $(this).animate({
        top: '0px',
        right:'0px'
    }, "slow");

});

一个使用transition属性的CSS解决方案,对JavaScript的依赖性较小: http//jsfiddle.net/d7tHU/10/

I guess what you want is this ' http://jsfiddle.net/d7tHU/11/ '.

$('.addToCart').click(function(){
    $(this).css('position','absolute');
    $(this).animate({
        top: -$(this).offset().top+'px',
        left: ($('#basket').offset().left - $('#basket').width()) +'px'
    }, "slow", function(){
        $(this).hide().appendTo('#basket')
           .css({position:'static', float:'right'})
           .fadeIn()
           .off('click');
        $('.price').html(parseFloat($('.price').html())+12.5);
    });    
});

The HTML little mod:

<div id='header'>
    <div id='basket'>
        <span style="padding-right:10px">Price: <span class="price">0</span>€</span>
    </div>
</div>

I think this might send you in the right direction.

http://jsfiddle.net/y7W4N/12/

You are targeting the inner div, target the parent as that is what you want to move ie $( ".addToCart").parent() ,

Also your script is changing position, ie left, but you have margin-left... so just work on top left etc.

EDIT a better version http://jsfiddle.net/b5Uux/ <-wrong link this is better

http://jsfiddle.net/b5Uux/1/

I have a working version for you here http://jsfiddle.net/ZET98/

What I did was changed the positions from margin-top and margin-left to top and right

I also changed your javascript to animate the when the parent is clicked and update the top css value

$( ".addToCart").parent()
.click(function() {
  $(this)
  .css({
      position:'fixed',
      top: $(this).offset().top - $(window).scrollTop()+'px'
  })
  .animate({
    right: $(this).children('.addToCart').outerWidth()+'px',
    top:"0",
  });
});

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