【问题标题】:Trigger event when certain scroll distance is reached jQuery达到一定滚动距离时触发事件jQuery
【发布时间】:2017-09-20 06:12:37
【问题描述】:
我有一个基于 vh 的网站,其中包含我想在滚动某个 vh 时显示的元素。我尝试使用带有变量的 if 语句来滚动距离,但它不会不断更新,所以它不起作用:
var distancePX = $(window).scrollTop();
var windowHeight = $(window).height();
var distanceVH = scroll/height * 100;
if (distance >= 170) {
//ACTIONS
};
我可以用什么来制作不断更新的上述版本?
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
使用纯 JS,您可以使用 onscroll 事件并将其绑定到正文。这是一个例子:
HTML
<body onscroll="myFunction()">
...
</body>
JS
var distancePX = $(window).scrollTop();
var windowHeight = $(window).height();
var distanceVH = scroll/height * 100;
function myFunction() {
if (distance >= 170) {
//ACTIONS
}
}
如果您喜欢非标记解决方案,也可以使用 jQuery 的 scroll() 方法。使用这种方法,您只需将 if 语句放在 scroll() 函数中。这是一个例子:
var distancePX = $(window).scrollTop();
var windowHeight = $(window).height();
var distanceVH = scroll/height * 100;
$("body").scroll(function(){
if (distance >= 170) {
//ACTIONS
}
});
希望这会有所帮助!
【解决方案2】:
jQuery 代码
$(window).scroll(function(){
if ($(this).scrollTop() >= 170) {
//actions...
} else {
//actions...
}
});