Javascript 当元素出现在“视口运行”函数中时
我试图编写一个函数,这样当我的Javascript 当元素出现在“视口运行”函数中时,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我试图编写一个函数,这样当我的元素进入视图时,一个函数就会附加到它 我的页面上有一系列元素,element1,element2,element3,我想编写一个函数,检查它们中的任何一个是否在视口中,而不是有一个大的if语句 我有以下几点,但这似乎不起作用,什么也没发生 var $findme = $('.section').each(); function Scrolled() { var findmeOffset = $findme.offset(), findmeT
元素进入视图时,一个函数就会附加到它
我的页面上有一系列元素,element1
,element2
,element3
,我想编写一个函数,检查它们中的任何一个是否在视口中,而不是有一个大的if语句
我有以下几点,但这似乎不起作用,什么也没发生
var $findme = $('.section').each();
function Scrolled() {
var findmeOffset = $findme.offset(),
findmeTop = findmeOffset.top,
scrollTop = $(document).scrollTop(),
visibleBottom = window.innerHeight;
if (findmeTop < scrollTop + visibleBottom) {
console.log('element is visible');
}
}
function Setup() {
var $top = $('#top'),
$bottom = $('#bottom');
$top.height(500);
$bottom.height(500);
$(window).scroll(function() {
Scrolled();
});
}
$(document).ready(function() {
Setup();
});
var$findme=$('.section').each();
函数滚动(){
var findmeOffset=$findme.offset(),
findmeTop=findmeOffset.top,
scrollTop=$(文档).scrollTop(),
VisibleBooth=window.innerHeight;
如果(findmeTop
演示
我认为问题与您申报的$findme有关。您正在传递一个HTML元素数组,但在Scrolled()中,您正在查找一个特定的顶部偏移量
如果您传递一个特定元素的id,而不是所有元素的类标识符,那么您提供的演示将起作用
也许您可以更新上面的代码,一次将一个标识符传递给Scrolled()。很抱歉,我不知道如何在应用程序的上下文中实现这一点。这里有一个非常好的解决方案:
您的主要问题是,您在滚动
事件处理程序中使用了$fimdme
,这导致它只应用于第一个元素。对没有参数的元素调用.each()
,根本没有效果
这是新代码。我对其进行了修改,因此,每次滚动时,无论是向下滚动还是向上滚动,当且仅当某个部分现在(在视口中)可见而以前不可见时,警报都会显示该部分的文本
var $findme = $('.section');
function Scrolled() {
$findme.each(function() {
var $section = $(this),
findmeOffset = $section.offset(),
findmeTop = findmeOffset.top,
findmeBottom = $section.height() + findmeTop,
scrollTop = $(document).scrollTop(),
visibleBottom = window.innerHeight,
prevVisible = $section.prop('_visible');
if ((findmeTop > scrollTop + visibleBottom) ||
findmeBottom < scrollTop) {
visible = false;
} else visible = true;
if (!prevVisible && visible) {
alert($section.text());
}
$section.prop('_visible', visible);
});
}
function Setup() {
var $top = $('#top'),
$bottom = $('#bottom');
$top.height(500);
$bottom.height(500);
$(window).scroll(function() {
Scrolled();
});
}
$(document).ready(function() {
Setup();
});
var$findme=$('.section');
函数滚动(){
$findme.每个(函数(){
变量$section=$(此),
findmeOffset=$section.offset(),
findmeTop=findmeOffset.top,
findmeBottom=$section.height()+findmeTop,
scrollTop=$(文档).scrollTop(),
VisibleBooth=window.innerHeight,
prevVisible=$section.prop(“U可见”);
如果((findmeTop>scrollTop+VisibleBooth)||
findmeBottom<滚动顶部){
可见=假;
}否则可见=真实;
如果(!prevVisible&&visible){
警报($section.text());
}
$section.prop(“可见”,可见);
});
}
函数设置(){
变量$top=$(“#top”),
$bottom=$(“#bottom”);
$top.height(500);
$bottom.height(500);
$(窗口)。滚动(函数(){
滚动();
});
}
$(文档).ready(函数(){
设置();
});
console中有错误吗?我添加了一个demo@PratikJoshinow,告诉您想要什么输出?检查我更新的小提琴=>当元素进入视图时,我希望它提醒元素的内容