1 回答
TA贡献1772条经验 获得超8个赞
在这个问题的帮助下:如何暂时禁用滚动?制定一个工作概念非常容易:
var keys = {37: 1, 38: 1, 39: 1, 40: 1};
// Select all input elements
var inputElems = document.getElementsByTagName('input');
// Turn them into an array
inputElems = Array.prototype.slice.call(inputElems);
// Create event listeners for input elements where type equals number
inputElems.forEach(function(elem) {
if(elem.type.toLowerCase() == 'number') {
elem.addEventListener('focus', disableScroll, false);
elem.addEventListener('blur', enableScroll, false);
}
});
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
document.addEventListener('wheel', preventDefault, {passive: false}); // Disable scrolling in Chrome
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
document.removeEventListener('wheel', preventDefault, {passive: false}); // Enable scrolling in Chrome
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
#container {
height: 300px;
width: 300px;
overflow: auto;
}
#inputs {
height: 1000px;
width: 300px;
}
<div id="container">
<div id="inputs">
<input type="text" value="This is a text input"/><br/>
<input type="number"/><br/>
<input type="number"/><br/>
<input type="number"/><br/>
<input type="number"/>
</div>
</div>
当焦点位于具有数字类型的输入字段之一时,它将禁用滚动。在模糊时,它会再次启用它。请记住,这不会阻止用户用鼠标手动向下拖动滚动条。禁用它是不可能的。
添加回答
举报