要实现的效果是在ie,chrome,firefox下监听滚轮触发事件。
源码:
window.onscroll=function(e){ var e =e || window.event; var scrolltop=document.documentElement.scrollTop||document.body.scrollTop; var box = $('#qa-head'); if(document.body.scrollTop >= 400){ box.addClass('fixed-head'); }else{ box.removeClass('fixed-head'); } }
模拟onscroll效果
if(document.addEventListener){ document.addEventListener('DOMMouseScroll',scrollFunc,false); } window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome var scrollFunc=function(e){ e=e || window.event; var t1=document.getElementById("qa-head"); if(t1.detail >= 400){ t1.addClass('fixed-head'); console.log('firefox'); }else{ t1.removeClass('fixed-head'); console.log('firefox lll'); } }
但是火狐模拟onscroll的这段代码控制台都没有输出,是什么原因哪里错了?
最大的問題應該是你先使用了函數才聲明吧....
var scrollFun c= function(e){
e = e || window.event
var t1 = document.getElementById("qa-head")
if(t1.detail >= 400) {
t1.addClass('fixed-head')
console.log('firefox')
} else {
t1.removeClass('fixed-head')
console.log('firefox lll')
}
}
window.onmousewheel = document.onmousewheel = scrollFunc; // IE/Opera/Chrome
if(document.addEventListener) {
document.addEventListener('DOMMouseScroll',scrollFunc,false)
}
函数表达式声明的函数在执行到函数体之前都是不可用的