Change Image on Scroll Position

后端 未结 3 873
臣服心动
臣服心动 2021-02-04 21:30

I would like to change an image on a certain scroll position. For example:

Scroll 100px show img1.jpg

Scroll 200px show img2.jpg

Scroll 300px show img3.j

3条回答
  •  名媛妹妹
    2021-02-04 22:23

    You can use the onScroll event to listen for scrolling, check at what position the scrollbar is and make the image change or whatever your heart desires. You can read more about onScroll event here. A basic code will be something like this:

    var onScrollHandler = function() {
      var newImageUrl = yourImageElement.src;
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      if (scrollTop > 100) {
         newImageUrl = "img1.jpg"
      }
      if (scrollTop > 200) {
         newImageUrl = "img2.jpg"
      }
      if (scrollTop > 300) {
         newImageUrl = "img3.jpg"
      }
      yourImageElement.src = newImageUrl;
    };
    object.addEventListener ("scroll", onScrollHandler);
    

    Of course yourImageElement should be replaced with the image element you want to change.

    If you have jQuery availble you can use the .scroll() method instead of the event listener and the .scrollTop() to get the scrollbar position.

    Also, you might want to look at some scroll/paralex libraries like skrollr.

提交回复
热议问题