禁用滚动所有输入类型编号

我想禁用所有输入类型编号上的所有滚动事件。


我看到了一些例子来做到这一点,但所有的例子都只针对一个元素


input = document.getElementById("the_number_input")

input.addEventListener("mousewheel", function(event){ this.blur() })

或者用 Jquery


$('form').on('focus', 'input[type=number]', function (e) {

  $(this).on('wheel.disableScroll', function (e) {

    e.preventDefault()

  })

})

$('form').on('blur', 'input[type=number]', function (e) {

  $(this).off('wheel.disableScroll')

})

有香草 javascript 的解决方案吗?


慕无忌1623718
浏览 137回答 1
1回答

料青山看我应如是

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

相关分类

JavaScript