经常会用到,判断浏览器窗口是否滚动到指定id的区域。
javascript代码:
function isScrolledIntoView(el) {
var elemTop = el.getBoundingClientRect().top;
var elemBottom = el.getBoundingClientRect().bottom;
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
return isVisible;
}
如果只想滚动到指定id区域的一部分,可以减去指定的像素,修改后如下:
function isScrolledIntoView(el) {
var elemTop = el.getBoundingClientRect().top;
var elemBottom = el.getBoundingClientRect().bottom - 345;
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
return isVisible;
}
jquery调用代码:
$(window).on('scroll', function() {
if (isScrolledIntoView(document.getElementById('points'))) {
alert('到了');
}
});
提示:points是指定区域的id。


