jQuery window.scroll move div vertical in opposite

2019-01-29 11:47发布

I have a div that scrolls down on the page scroll and when I scroll up the div scrolls up. I would like the opposite

This is the code:

// SCROLL BUTTON
// -- iPhone picture should scroll in when down and down when up
    jQuery(window).scroll(function(){   
        jQuery(".iphonepic").stop().animate({ "top": (jQuery(window).scrollTop() - 0.00) + "px"}, "slow"); 
    });

So when you scroll down, the div should go up vertically not the same as the scroll direction.

Fiddle demo: http://jsfiddle.net/khaleelm/sQZ9G/7/

Update

I also want to limit the DIV not to go higher than -150px, trying

if ( parseInt(jQuery(".iphonepic").css("top"), 10) >= -150 ) {

1条回答
贪生不怕死
2楼-- · 2019-01-29 12:06

You can do:

{ top: -jQuery(window).scrollTop() + 'px' }

Also, a few tips to make it more efficient.

You're calling jQuery(window) and jQuery('.iphonepic') on every scroll event, that's really expensive. Just do:

var $window = jQuery(window), $iPhonePic = jQuery('.iphonepic')

$w.on('scroll', function(){

  var top = -$window.scrollTop();

  if ( top < -150 ) {
    top = -150;
  }

  $iPhonePic.stop().animate({
    top: top + 'px'
  }, "slow");
});
查看更多
登录 后发表回答