js实现鼠标滑动到某个div禁止滚动
本文实例为大家分享了js实现鼠标滑动到某个div禁止滚动的具体代码,供大家参考,具体内容如下
项目中碰到一个场景就是当鼠标滑倒某个div的时候,滑动鼠标页面不再滚动。
这里主要是当鼠标滑动到该div时,监听滚轮事件并通过preventDefault()事件来阻止滚动事件,以下是例子
eg:
#wrap{
position:absolute;
top:200px;
background:#000000;
font-size:40px;
width:50vw;
text-align:center;
color:#ffffff;
line-height:300px;
height:300px;
}
鼠标移动进入该区域,页面禁止滚动
window.onload=function(){
for(i=0;i<50;i++){
varx=document.createElement('div');
x.innerHTML="test
";
document.body.appendChild(x);
}
function$(x){
returndocument.getElementById(x);
};
$("wrap").onmousewheel=functionscrollWheel(e){
varsl;
e=e||window.event;
if(navigator.userAgent.toLowerCase().indexOf('msie')>=0){
event.returnValue=false;
}else{
e.preventDefault();
};
};
if(navigator.userAgent.toLowerCase().indexOf('firefox')>=0){
//firefox支持onmousewheel
addEventListener('DOMMouseScroll',
function(e){
varobj=e.target;
varonmousewheel;
while(obj){
onmousewheel=obj.getAttribute('onmousewheel')||obj.onmousewheel;
if(onmousewheel)break;
if(obj.tagName=='BODY')break;
obj=obj.parentNode;
};
if(onmousewheel){
if(e.preventDefault)e.preventDefault();
e.returnValue=false;//禁止页面滚动
if(typeofobj.onmousewheel!='function'){
//将onmousewheel转换成function
eval('window._tmpFun=function(event){'+onmousewheel+'}');
obj.onmousewheel=window._tmpFun;
window._tmpFun=null;
};
//不直接执行是因为若onmousewheel(e)运行时间较长的话,会导致锁定滚动失效,使用setTimeout可避免
setTimeout(function(){
obj.onmousewheel(e);
},
1);
};
},
false);
};
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。