用window.onscoll实现滑动固定顶部功能,出现刚滑动就会执行的问题
window.onscroll = function () {
if (document.documentElement.scrollTop || document.body.scrollTop > 2000) {
totop.style.transition = 'height 1s'
totop.style.height = '100px'
}
else {
totop.style.transition = 'height 0s'
totop.style.height = 0
}
}
但是下面又可以
window.onscroll = function () {
var t = document.documentElement.scrollTop || document.body.scrollTop
if (t > 2000) {
totop.style.transition = 'height 1s'
totop.style.height = '100px'
}
else {
totop.style.transition = 'height 0s'
totop.style.height = 0
}
}
这是为什么啊??
你第一个的判断条件:document.documentElement.scrollTop || document.body.scrollTop > 2000
它是这样执行的:如果存在document.documentElement.scrollTop或者document.body.scrollTop > 2000都会进入执行if语句
如果改成:document.documentElement.scrollTop>2000 || document.body.scrollTop > 2000
和你下面的效果就一样了
两个方法的判断判断条件不一样的。上面是scrollTop或者srollTop>2000,满足其一就会执行,但下面是具体取值,然后用于判断。你可以在代码上加一个debugger,然后在断点中调试一下。希望对你有帮助。