在滚动位置更改图像 [英] Change Image on Scroll Position

查看:165
本文介绍了在滚动位置更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在某个滚动位置更改图像。例如:

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

Scroll 100px show img1.jpg

Scroll 100px show img1.jpg

Scroll 200px show img2.jpg

Scroll 200px show img2.jpg

Scroll 300px show img3.jpg

Scroll 300px show img3.jpg

在这里我找到了一个例子我的意思。

Here I found an example what I mean.

任何想法?

推荐答案

您可以使用 onScroll 事件来监听滚动,检查滚动条处于什么位置并使图像发生变化或者您想要的任何内容。您可以在此处了解有关onScroll事件的更多信息。基本代码将是这样的:

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);

当然 yourImageElement 应该替换为你要改变的图像元素。

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

如果你有jQuery可用,你可以使用 .scroll() 方法而不是事件监听器和 .scrollTop() 获取滚动条位置。

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

另外,您可能希望查看一些滚动/阅读库,例如 skrollr

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

这篇关于在滚动位置更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆