简体   繁体   中英

Changing the position of div on scroll

I want an image to scroll up as I scroll down the page. I could do that quite easily, but the issue I'm having is that in the jQuery I'm changing the image's CSS, specifically its transform property. But I'm using the transform property already, to center align the image.

Code:

.planeImg {
    position: absolute;
    display: block;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: url("../images/plane.png");
    background-size: contain;
    background-repeat: no-repeat;
    z-index: 99;
    height: 80px;
    width: 300px;
}

$(window).on("scroll", function() {
    var wScroll = $(this).scrollTop();
    $('.planeImg').css({'transform' : 'translate(0px, -'+ wScroll /2 +'%)'})
});

So because I'm using the transform property to center align the image, the jQuery is buggering up the position of my image.

I changed the calculation of wScroll to make the scrolling of the image follow the scrolling of the page. Please, let me know if this helps.

Fiddle

javascript

$(window).on("scroll", function() {
  var wScroll = ($(this).scrollTop() / $(window).height()) + 50;
  $('.planeImg').css({
    'transform': 'translate(-50%, -' + (wScroll) + '%)'
  })
});

CSS

.planeImg {
  position: absolute;
  display: block;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: url("https://www.google.be/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
  background-size: contain;
  background-repeat: no-repeat;
  z-index: 99;
  height: 80px;
  width: 300px;
}

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