如何在不使用插件的情况下检查视口中的哪个部分
How to check which section is in the viewport without the use of a plugin?
我正在创建一个包含多个部分的新网站。每个节都有一个标题,其中包含一个1标题(h1)。此外,每个部分都有一个id
属性。
我正在寻找的是如何在每个部分的标题中添加最小视差效果。当节在视口中时,它应该从为标头的margin-top
设置动画开始,例如x像素量,例如5或10px。
我想检查哪个部分在浏览器的视口中,如果是,请开始视差动画。如果可能的话,不需要任何插件。我该怎么做?
我想到了以下内容:
$(window).scroll(function() {
// Get the offset of the window from the top of page
var windowPos = $(window).scrollTop();
$('.main').find('section').each(function() {
var anchorId = $(this);
var target = $(anchorId.attr("id"));
var offsetTop = target.position().top;
if (offsetTop <= windowPos && offsetTop + target.height() > windowPos) {
console.log(this);
// Parallax function here
}
});
});
不幸的是,我收到错误:Uncaught TypeError: Cannot read property 'top' of undefined
。
因此,我希望代码返回部分的id,然后在视口中可见。然后开始动画该部分的标题。
提前谢谢。现场演示:http://codepen.io/anon/pen/xZwpzX?editors=101
您的this语句:
var target = $(anchorId.attr("id"));
var offsetTop = target.position().top;
应该是:
var target = $("#"+anchorId.attr("id"));
var offsetTop = target.offset().top;
由于anchorId.attr('id')
将返回作为字符串的id
,因此您需要为id预加#
或为class预加.
。此外,您在this
中有元素,可以使用它。
试试这个,希望它能起作用:
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
$(window).scroll(function() {
$('.main').find('section').each(function() {
if (isElementInViewport($(this))) {
console.log($(this));
// Parallax function here
}
});
})
如何判断DOM元素在当前视口中是否可见?
相关文章:
- 将视口底部滚动到元素底部
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- 使用条件语句,使 jquery fadeIn/fadeOut 仅在视口 >= 480px 时才有效
- 宽度为100%的CSS元素位于视口之外
- CSS3:当页面向下滚动到第一个视口时,是否可以在元素上触发转换
- 如何设置浏览器视口大小
- Javascript em根据窗口/视口尺寸调整大小,不影响文档样式的text/css
- 检测视口并重定向到不同的主页
- 如何在按住鼠标按钮且光标在视口外时检测鼠标离开
- iOS iPad平板电脑渲染视口不正确
- 移动设备上的视口问题
- 视口大小更改时自动刷新页面
- 在移动设备上获取视口大小
- 在 ReactJS 中获取视口/窗口高度
- 使jquery延迟加载插件在视口内工作
- 检查视口是否缩放
- 检查侧载视口的宽度,如果小于 X,则向主体添加类
- JavaScript检查元素是否在顶视口之外
- 如何使用javascript检查视口是否小于一定的宽度
- JavaScript - 检查绝对坐标(左、上、右、下)是否在当前视口上可见