根据浏览器窗口中容器 div 的位置移动绝对定位的图像
我有一个具有相对位置的 div (div 1)。它包含一个具有绝对位置的图像(显示为绿色块),默认情况下隐藏在浏览器窗口左侧。
我想这样做,以便当用户向下滚动时 div 1 位于浏览器窗口的中心时,图像会从左侧稍微移入并显示在屏幕上。当用户开始向下滚动经过 div 1 时,我希望图像移回到其原始的屏幕外位置。
我附上了一张图片,试图让其更有意义。
我感觉使用 JavaScript 或 jQuery 是可能的,但我不确定如何实现。任何帮助将不胜感激。
伊恩
I have a div with a relative position (div 1). It contains an image (shown as the green block) with an absolute position which by default is hidden way off to the left of the browser window.
I'd like to make it so that when div 1 is in the center of the browser window as the user scrolls down, the image is moved in slightly from the left and appears on the screen. As the user begins to scroll down past div 1, I'd like the image to move back to its original offscreen position.
I have attached a picture to try and make a bit more sense.
I have a feeling this is possible using JavaScript or jQuery but I'm not sure how. Any help would be greatly appreciated.
Ian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将处理程序绑定到窗口的
scroll
事件,并测量用户向下滚动页面的距离的比率 - 然后相应地定位图像。我构建了一个粗略原型;您应该能够调整大小和位置以使其适合您。原型的 JS 依赖于上面链接的 JSFiddle 中的 HTML 和 CSS,如下所示:
You'll want to bind a handler to the
scroll
event of the window, and measure the ratio of how far down the page the user has scrolled - then, position the image accordingly. I built a rough prototype; you should be able to tweak sizes and positions to make it work for you.The JS for the prototype, which depends on the HTML and CSS in the JSFiddle linked above, is as follows:
您可能希望将图像放置在滚动条上。您基本上会检查 div 的位置,将图像的顶部设置为与 div 相同,并将左侧设置为您喜欢的任何位置。您可以使用 jquery animate 来使其“移动”到该位置。然后,您必须设法执行滚动停止事件(该事件不存在),并再次隐藏图像。请参阅:http://james.padolsey.com/javascript/special -scroll-events-for-jquery/ 用于滚动停止实现(摘自下面的帖子)。
您可能想通读jQuery - 滚动时淡出/“滚动停止”时淡入< /a>
You would want to position the image on scroll. You would basically check what the position of the div is, set the top of the image to the same as the div, and set the left to whatever you like. you could use jquery animate for this to make it "move" to that position. You then would have to manage to do an scrollstop event (which doesn't exist), and hide the image again. See: http://james.padolsey.com/javascript/special-scroll-events-for-jquery/ for scrollstop implementation (taken from the below post).
You might want to read through jQuery - fadeOut on Scroll / fadeIn on "scrollstop"