[英]Load Javascript when div is in viewport
这就是 HTML 文件中的 Div
<div class="inViewport">
只有当 div 在视口中时才应该加载此脚本
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
ToxProgress.create();
ToxProgress.animate();
});
</script>
这是您应该查看的内容: 检查滚动后元素是否可见
这是一个演示此技术的示例: http://jsfiddle.net/XYS2G/ - 只需尝试滚动结果 window。
HTML:
<div class="indicators">
<span class="indicator" data-id="section1">section1</span>
<span class="indicator" data-id="section2">section2</span>
<span class="indicator" data-id="section3">section3</span>
<span class="indicator" data-id="section4">section4</span>
<span class="indicator" data-id="section5">section5</span>
<span class="indicator" data-id="section6">section6</span>
</div>
<div class="sections">
<div class="section" id="section1">section1</div>
<div class="section" id="section2">section2</div>
<div class="section" id="section3">section3</div>
<div class="section" id="section4">section4</div>
<div class="section" id="section5">section5</div>
<div class="section" id="section6">section6</div>
</div>
CSS:
.indicators { position: fixed; }
.section { height: 150px; }
Javascript:
function isScrolledIntoView(elem)
{
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
function refreshIndicators() {
$('.indicator').each(function () {
if (isScrolledIntoView($('#' + $(this).attr('data-id')))) {
$(this).css('color', 'red');
} else {
$(this).css('color', 'black');
}
});
}
refreshIndicators();
$(window).bind('scroll', refreshIndicators);
您好,感谢您的快速回复。 但是我想在div进入视口时运行脚本,因为有一个animation技能圈。
那是我的 div 与技能栏 cirlce inlcuded
<div id="inViewport">
那是新剧本
<script type="text/javascript">
if (document.getElementById("inViewport")){
ToxProgress.create();
ToxProgress.animate();
}
</script>
像这样:但不工作......对不起,我是一个菜鸟
<script type="text/javascript">
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
window.addEventListener("scroll resize", function() {
if (isInViewport(document.getById("inViewport"))) {
ToxProgress.create();
ToxProgress.animate();
}
});
</script>
我认为这个 function 会帮助你:
function isInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
(取自此处)然后,您需要监听滚动事件,并且每次用户滚动时,通过调用上面的 function 来检查元素是否在视口中。 样本:
window.addEventListener("scroll resize", function() {
if (isInViewport(document.getById("inViewport"))) {
ToxProgress.create();
ToxProgress.animate();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.