有办法缩短这个时间吗?
var scrollPos = function() {
var bodyTopPos =
header.style.top <
( document.body.scrollTop || document.documentElement.scrollTop ) -91;
header.setAttribute('class', bodyTopPos ? 'sticky' : '');
}();
window.onscroll = function() {
var bodyTopPos =
header.style.top <
( document.body.scrollTop || document.documentElement.scrollTop ) -91;
header.setAttribute('class', bodyTopPos ? 'sticky' : '');
}
我尝试编写以下内容,但它似乎会自动将 header 类设置为粘性。
var scrollPos = function() {
var bodyTopPos =
header.style.top <
( document.body.scrollTop || document.documentElement.scrollTop ) -91;
header.setAttribute('class', bodyTopPos ? 'sticky' : '');
}();
window.onscroll = scrollPos();
你可以看到我的工作 fiddle 示例 HERE
最佳答案
很简单,只需将其设为一个命名函数,调用它,并将其设置为 onscroll
处理程序即可。
function scroll() {
var bodyTopPos =
header.style.top <
( document.body.scrollTop || document.documentElement.scrollTop ) -91;
header.setAttribute('class', bodyTopPos ? 'sticky' : '');
}
scroll();
window.onscroll = scroll;
关于javascript - JS : Making two functions do the same thing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27880545/