通过用户滚动了多少来检测 [英] Detecting by how much user has scrolled

查看:78
本文介绍了通过用户滚动了多少来检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上有图片弹出功能,以便在用户点击网页上的较小版本时向用户显示完整的分辨率图片。

I have an image pop-up ability on my website, in order to show users the full resolution picture when they click on a smaller version on the page.

这是当前的 CSS ,它定位它:

This is the current CSS that positions it:

div#enlargedImgWrapper {
    position: absolute;
    top: 30px;
    left: 55px;
    z-index: 999;
}

现在的问题是,如果我点击页面下方的图片,窗口仍然显示在页面的左上角,在我向上滚动之前,我看不到它。我需要它相对于窗口显示,无论它相对于文档的当前位置。

The problem now is that if I click on an image further down the page, the window still appears in the top left corner of the page, where I can't see it until I scroll back up. I need it to appear relative to the window, whatever its current position relative to the document is.

注意:我不想使用 position:fixed; ,因为某些图片可能比屏幕高,因此我希望用户能够沿着图片滚动。

Note: I don't want to use position: fixed; as some images might be taller than the screen, so I want users to be able to scroll along the image as well.

我的想法是使用JS更改顶部值:

My idea was to use JS to change the top value:

var scrollValue = ???;
document.getElementById('enlargedImgWrapper').style.top = scrollValue+30 + 'px';

如何检测用户向下滚动页面的大小( var scrollValue )?

或者有更好的方法吗?

How can I detect by how much the user has scrolled down the page (var scrollValue)?
Or is there a 'better' way to do this?

推荐答案

纯JavaScript使用 scrollTop scrollLeft

Pure JavaScript uses scrollTop and scrollLeft:

var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

https://developer.mozilla.org/en-US/docs/Web/API/Element.scrollTop

jQuery 版本:

var scrollLeft = $(window).scrollLeft() ;
var scrollTop = $(window).scrollTop() ;

您需要的是:

document.getElementById('enlargedImgWrapper').style.top = (scrollTop+30) + 'px';

这篇关于通过用户滚动了多少来检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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