如果我的网页的用户在其上达到某个点,是否可以运行一个函数?
我尝试与不同的divs进行网站,或者对我来说是部分。如果我到达其中之一的顶部,则应该安装本学期日志。如果您问,则滚动量等于设备的ScreenHeight的1%。
let Point1 = false;
document.addEventListener("scroll", e=> {
if (document.documentElement.scrollTop >= 150*ScrollHeight) {
if (Point1 == false){
Point1 = true;
Point1F();
};
}
})
function Point1F() {
console.log("U've done it');
}
但这对我来说并不折腾。
I try do a webite with different divs or for me they are sections. If I reached the top of one of these it should console log this term. If u ask, ScrollHeight is equal to 1% of the devices' screenheight.
let Point1 = false;
document.addEventListener("scroll", e=> {
if (document.documentElement.scrollTop >= 150*ScrollHeight) {
if (Point1 == false){
Point1 = true;
Point1F();
};
}
})
function Point1F() {
console.log("U've done it');
}
But its not woking for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码有效,因为我认为为什么您看不到.log()的问题是因为您没有达到它。
如果卷轴是(如您所说)“设备的1%ScreenHeight”,则需要HTML高度〜3倍您的屏幕高度;
PS
不要使用以大写字母开头的变量/函数的名称,请在; y上用于构造函数函数或类。
Your code works, as i think the problem why you don't see your .log() is because you didn't reach it.
If scrollHeight is (as you said) "1% of the devices' screenheight", then you need html height to be ~ 3x your screen height;
P.S.
Don't use variable's/function's names starting with a capital letter, use it on;y for constructor functions or classes.
交叉点观察者API
使用滚动位置时,当您具有单个触发点时,可以使用滚动位置。但是,当有多个触发点(如问题所示)并且它们在不同设备上的位置不一致时,则相交观察者API 是一个有用的解决方案。
mdn:
您可以在文档或容器元素上创建一个观察者,然后添加要观看的元素。当元素达到阈值设置时,触发回调。
演示片段
摘要显示了如何在滚动进出时观察到不同的部分。
Intersection Observer API
Using scroll position is fine when you have a single trigger point. However, when there are multiple trigger points (as the question suggests) and they are not in a consistent position on different devices, then the Intersection Observer API is a useful solution.
MDN:
You create an observer on the document or a container element and then add the elements you want to watch. And the callback is triggered when an element reaches the threshold setting.
Demo Snippet
The snippet shows how to observe different sections as they scroll in and out of view.