首页 > 解决方案 > 如何在向下滚动网页时更改图片?

问题描述

我正在一个图片位于固定位置的网站上工作。滚动时图片应更改。我的 img 文件夹中有 6 张图片,第一张图片在我的索引文件中实现。现在我希望图片更改 5 次,例如:我正在向下滚动并以 20% 的 PIC1 更改为 PIC2。然后在 40% 时将 PIC2 更改为 PIC3,依此类推。

我尝试了javascript但失败了。


var onScrollHandler = function() {
  var newImageUrl = Pic1.svg;
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  if (scrollTop > 100) {
     newImageUrl = "pic2.svg"
  }
  if (scrollTop > 200) {
     newImageUrl = "pic3.svg"
  }
  if (scrollTop > 300) {
     newImageUrl = "pic4.svg"
  }
  if (scrollTop > 400) {
     newImageUrl = "pic5.svg"
  }
  if (scrollTop > 500) {
     newImageUrl = "pic6.svg"
  }
  Pic1.svg = newImageUrl;
};
object.addEventListener ("scroll", onScrollHandler);

我希望这是可以理解的,有人可以帮助我直到明天。祝你有美好的一天,无论如何谢谢你!

标签: javascripthtml

解决方案


这是一些接近您要求的代码。在任何生产代码中使用它之前,您可能需要对其进行适当的测试,但希望它会为您指明正确的方向。

所有的魔法都在 javascript 代码中。

// The available scroll space in the browser window is evaluated and 
// assigned to h here
var h = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) - window.innerHeight;

// h is divided into 5 equals parts
var diff = h / 5;
var processing = false;

// variable to keep track of how far the user has scrolled so image can be changed
var diff_tracker = 0;

// variable to keep track of the current image being displayed
var current_image_index = 1;

var last_known_scroll_position = 0;


// this function changes the image displayed depending the scroll position 
function changeImage(scroll_pos) {
  if (scroll_pos === 1) {
    document.getElementById("image").src = "https://www.w3schools.com/html/pic_trulli.jpg";
  } else if (scroll_pos === 2) {
    document.getElementById("image").src = "https://www.w3schools.com/Html/img_girl.jpg";
  } else if (scroll_pos === 3) {
    document.getElementById("image").src = "https://www.w3schools.com/css/img_5terre_wide.jpg";
  } else if (scroll_pos === 4) {
    document.getElementById("image").src = "https://www.w3schools.com/w3css/img_snowtops.jpg";
  } else if (scroll_pos === 5) {
    document.getElementById("image").src = "https://www.w3schools.com/w3css/img_nature.jpg";
  }
}

// on scroll, this listener fires and updates the image being displayed as required
window.addEventListener('scroll', function(e) {
  var scroll_position = window.scrollY;

  if (!processing) {
    window.requestAnimationFrame(function() {
      if (last_known_scroll_position === 0) {
        last_known_scroll_position = scroll_position;
      } else {
        diff_tracker += scroll_position - last_known_scroll_position;
        if (diff_tracker >= 0) {
          while (diff_tracker >= diff) {
            diff_tracker -= diff;
            current_image_index++;
            changeImage(current_image_index);
          }
        } else {
          while (diff_tracker < -diff) {
            diff_tracker += diff;
            current_image_index--;
            changeImage(current_image_index);
          }
        }

      }

      last_known_scroll_position = scroll_position;
      processing = false;
    });

    processing = true;
  }
});

function recalculate() {
    h = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) - window.innerHeight;
    diff = h / 5;
}

// if the window is resized, the scrolling height and diff variable are recalculated
window.onresize = recalculate;
<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    div.sticky {
      position: -webkit-sticky;
      position: sticky;
      top: 0;
      padding: 70px;
      font-size: 20px;
    }
  </style>
</head>

<body>

  <h2>Scroll Down to See the Effect</h2>
  <div class="sticky"><img id="image" width=300 height=300 src="https://www.w3schools.com/html/pic_trulli.jpg" /> </div>


  <h2>Some random text to enable scroll..</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus
    vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, congue eget, auctor vitae massa. Fusce luctus vestibulum augue
    ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet
    sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fst hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis.
    Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet,
    nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu,
    lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.</p>

</body>

</html>


推荐阅读