JavaScript 如何禁用textarea中的箭头键
给定一个包含元素的HTML元素,并且任务是使用JavaScript禁用通过箭头键滚动。
方法1
- 在窗口上添加一个 onkeydown 事件监听器。
- 如果事件发生,则检查按键是否为箭头键。
- 如果按下箭头键,则阻止其默认行为。
示例: 此示例实现了上述方法。
HTML代码
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<textarea id="t">
JavaScript was once upon a time used
only in client side(browser), but node
js (execution engine/run time/web
server) have made possible to run
javascript on server side. JavaScript
has stormed the web technology and
nowadays small software ventures to
fortune 500, all are using node js
for web apps.
</textarea>
<br>
<button onclick="gfg_Run()">
click here
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to disable"
+ " scrolling through arrow keys.";
function gfg_Run() {
window.addEventListener("keydown", function(e) {
if([32, 37, 38, 39, 40].indexOf(e.keyCode) > -1){
e.preventDefault();
}
}, false);
el_down.innerHTML =
"Scrolling from arrow keys is disabled.";
}
</script>
输出:
方法2
- 这个示例与上一个示例非常相似。它也维护一个按下的按键数组,并在抬起按键事件发生时从数组中移除按键。
- 在窗口上添加一个 onkeydown 事件监听器。
- 如果事件发生,则检查按键是否是箭头键。
- 如果按下了箭头键,则阻止其默认行为。
示例: 这个示例实现了上述方法。
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<textarea id="t">
JavaScript was once upon a time used
only in client side(browser), but node
js (execution engine/run time/web
server) have made possible to run
javascript on server side. JavaScript
has stormed the web technology and
nowadays small software ventures to
fortune 500, all are using node js
for web apps.
</textarea>
<br>
<button onclick="gfg_Run()">
click here
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to disable"
+ " scrolling through arrow keys.";
function gfg_Run() {
var key = {};
window.addEventListener("keydown", function(e) {
key[e.keyCode] = true;
switch(e.keyCode){
case 37: case 39: case 38: case 40:
case 32: e.preventDefault(); break;
default: break;
}
}, false);
window.addEventListener('keyup', function(e){
key[e.keyCode] = false;
}, false);
el_down.innerHTML =
"Scrolling from arrow keys is disabled.";
}
</script>
输出: