简体   繁体   English

更改div在滚动条上的位置

[英]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. 我可以很容易地做到这一点,但是我遇到的问题是,在jQuery中,我正在更改图像的CSS,特别是其transform属性。 But I'm using the transform property already, to center align the image. 但是我已经在使用transform属性,以使图像居中对齐。

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. 因此,由于我使用了transform属性来使图像居中对齐,因此jQuery困扰了我图像的位置。

I changed the calculation of wScroll to make the scrolling of the image follow the scrolling of the page. 我更改了wScroll的计算,以使图像的滚动跟随页面的滚动。 Please, let me know if this helps. 请让我知道这可不可以帮你。

Fiddle 小提琴

javascript javascript

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

CSS 的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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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