当用户滚动位置到达时,将 javascript 加载到 div
Load javascript into div when user scroll position reaches it
我想让脚本仅在用户到达时才加载到 div 中。我正在尝试使用 jQuery 来完成此操作,但没有成功。也许你能帮忙。这是代码:
var scrollFromTop = $("#float_div_id").offset().top;
$(document).scroll(function () {
if ($(this).scrollTop() > scrollFromTop) {
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.src = 'javascript code src which i want to append on scroll';
document.getElementById('float_div_id').appendChild(s);
}
});
你应该看看waypoint library。当用户在特定元素上滚动时它会触发一个事件,并且您可以执行一些编码(诱人?)
var waypoint = new Waypoint({
element: document.getElementById('thing'),
handler: function(direction) {
alert('You have scrolled to a thing')
}
})
然后在滚动之后,你应该使用 $.getScript() 和一个单独的 JS 文件:
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
$.getScript('/javascript/myscript.js');
如果某些代码需要您的新 js 文件,请小心使用异步:
$.getScript('/javascript/myscript.js', function() {
// do something here
});
让我知道这是否适合你:D
在您的情况下,$(this).scrollTop()
会小于 scrollFromTop
。
将您的 if 条件更改为此并重试:
if ($(this).scrollTop() + $(window).height() > scrollFromTop)
我想让脚本仅在用户到达时才加载到 div 中。我正在尝试使用 jQuery 来完成此操作,但没有成功。也许你能帮忙。这是代码:
var scrollFromTop = $("#float_div_id").offset().top;
$(document).scroll(function () {
if ($(this).scrollTop() > scrollFromTop) {
var s = document.createElement('script');
s.setAttribute('type', 'text/javascript');
s.src = 'javascript code src which i want to append on scroll';
document.getElementById('float_div_id').appendChild(s);
}
});
你应该看看waypoint library。当用户在特定元素上滚动时它会触发一个事件,并且您可以执行一些编码(诱人?)
var waypoint = new Waypoint({
element: document.getElementById('thing'),
handler: function(direction) {
alert('You have scrolled to a thing')
}
})
然后在滚动之后,你应该使用 $.getScript() 和一个单独的 JS 文件:
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
$.getScript('/javascript/myscript.js');
如果某些代码需要您的新 js 文件,请小心使用异步:
$.getScript('/javascript/myscript.js', function() {
// do something here
});
让我知道这是否适合你:D
在您的情况下,$(this).scrollTop()
会小于 scrollFromTop
。
将您的 if 条件更改为此并重试:
if ($(this).scrollTop() + $(window).height() > scrollFromTop)