我有一个只有一页的网站,带有固定导航和使用滚动脚本,非常类似于这个: http://www.ivanjevremovic.in.rs/live/temptation/single/orange/index-cycle-slider.html
我正在寻找一种方法来检查窗口中可见的部分以在使用浏览器滚动条时设置导航的活动状态,有什么想法吗?
我有一个只有一页的网站,带有固定导航和使用滚动脚本,非常类似于这个: http://www.ivanjevremovic.in.rs/live/temptation/single/orange/index-cycle-slider.html
我正在寻找一种方法来检查窗口中可见的部分以在使用浏览器滚动条时设置导航的活动状态,有什么想法吗?
以下是您需要的所有变量...
var $myElt = $('.myElement'); // whatever element you want to check
var $window = $(window); // the window jQuery element
var myTop = $myElt.offset().top; // the top (y) location of your element
var windowTop = $window.scrollTop(); // the top of the window
var windowBottom = windowTop + $window.height(); // the bottom of the window
为确保您的元素在窗口范围内...
if (myTop > windowTop && myTop < windowBottom) {
// element is in the window
} else {
// element is NOT in the window
// maybe use this to scroll...
// $('html, body').animate({scrollTop: myTop}, 300);
}
jQuery 参考资料:
使用$('#element').offset().top;
来检测元素顶部位置。
$(window).scrollTop();
用于检测当前滚动位置。
然后,使用$(window).height();
来检测当前窗口高度。
接下来,您只需要进行一些简单的数学计算即可。
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
}
源代码:滚动后检查元素是否可见
请查看以下的lazyload插件:
http://plugins.jquery.com/files/jquery.lazyload.js__6.txt
以“返回相对于当前视图的项目状态”的注释开头的部分检查元素是否在视口中可见。
$('html').position().top;
例如:
$(document).bind("scroll", checkLink);
function checkLink(){
/* Position will checked out after 1 sec when user finish scrolling */
var s = setTimeout(function(){
var docHeight = $('html').position().top;
var allLinks = $('.navigation a');
if ( docHeight < 0 && docHeight <= -1000 ) {
allLinks.removeClass('active');
$('a.firstlink').addClass('active');
} else
if ( docHeight < -1000 && docHeight <= -2000 ) {
allLinks.removeClass('active');
$('a.secondlink').addClass('active');
} else { /* .... */ }
$(document).bind("scroll", checkLink);
}, 1000);
$(document).unbind('scroll');
}
但是你们的例子中的人并没有长时间坚持这个 :) 他们只是在点击时切换类
$('#navigation').localScroll();
$('#navigation li a').click( function () {
$('#navigation li a').removeClass("active");
$(this).addClass("active");
});
现在可以使用IntersectionObserver和纯JavaScript来实现。
其他解决方案的问题在于它们会触发太多次。
例如,你可以这样做:
var observer = new IntersectionObserver(function(entries) {
if(entries[0].isIntersecting === true) {
console.log('Element is in the window');
} else {
console.log("Element is not in the window");
}
});
observer.observe(document.querySelector(".myObject"));