[英]How to check if element was in viewport once
I'm trying to check if element was seen in viewport once, if seen do nothing, if not continue the function.我正在尝试检查是否在视口中看到过一次元素,如果看到什么也不做,如果没有继续 function。
.isInViewport()
- check if the element is in viewport, returns true or false. .isInViewport()
- 检查元素是否在视口中,返回真或假。
var index
- index if seen once, if seen once it will be equal to 1 if not seen once be equal to 0. var index
- 如果见过一次的索引,如果见过一次它将等于 1 如果没有见过一次等于 0。
$.fn.isInViewport = function (){
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
//Get Scale
var index = 0;
window.onscroll = function(e) {
if($('footer').isInViewport()){
index++;
}
if(index == 0){
if(this.oldScroll > this.scrollY){
// Do nothing while scrolling up
}
else{
scale = scale + 0.01; // Increase while scroll down
}
this.oldScroll = this.scrollY;
}
}
Currently, the user reaches to footer
tag, the index is 1. But when scrolling back the index is 0 back.目前,用户到达footer
标签时,索引为 1。但向后滚动时,索引为 0。
How can I check if viewport was seen once?如何检查视口是否被看到过一次?
I figured out, once isInViewport
is false, the window.onscroll
event will refresh and remove the index.我发现,一旦isInViewport
为假, window.onscroll
事件将刷新并删除索引。
So I have added class to the element, so no matter if the element is in viewport, I will still have index if seen or not.所以我在元素中添加了 class ,所以无论元素是否在视口中,无论是否看到我都会有索引。
var index = 0;
window.onscroll = function(e) {
if($('footer').isInViewport()){
$('footer').addClass('viewport');
}
if($('footer').hasClass('viewport')){
index++;
}
if(index == 0){
if(this.oldScroll > this.scrollY){
// Do nothing while scrolling up
}
else{
scale = scale + 0.005; // Increase while scroll down
}
this.oldScroll = this.scrollY;
}
console.log(index);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.