我要加载chart.html
当我滚动<div class="loadChart">
,并在第一时间加载它。
var loadChart = $('.loadChart').offset().top;
console.log(loadChart); //loadChart top is 1532
我用setTimeout
控制,但我仍然有麻烦。
这是我的代码↓
var timer;
window.onscroll = function(){
var scrollPos = $(document).scrollTop();
if(scrollPos>=1532){
window.clearTimeout(timer);
timer = window.setTimeout(function() {
$('.loadChart').load('chart.html');
}, 1000);
}
}
我如何使用 jQuery 和 JavaScript 来做到这一点?
您需要做的是将窗口高度添加到滚动位置,以便在 div 从底部进入视口时立即加载内容。否则,只有当您将内容滚动到接触视口顶部时,内容才会加载。
你也不需要setTimeout
除非您出于性能原因想要实施某种频率上限(但这不是您实施它的方式)。
然后确保在加载内容后取消设置 onscroll 回调。 (或者,如果您需要它用于其他内容,请设置数据属性或变量(如果内容已加载)并检查它是否已加载load()
必须触发或不触发。
var loadChart = $('.loadChart'),
loadChartTop = $('.loadChart').offset().top;
window.onscroll = function(){
var scrollPos = $(document).scrollTop();
if(scrollPos + window.innerHeight >=loadChartTop){
console.log("would load now!");
loadChart.load('chart.html');
// remove onscroll callback
window.onscroll = null;
}
}
.loadChart {
background: red;
text-align: center;
color: #ffffff;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
other content<br>
<div class="loadChart">
chart will be here!
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)