当使用选项卡按钮浏览页面时,当光标位于锚标签链接时,在锚标签链接时输入空格按钮时,我必须使用 JavaScript 或 jQuery 使空格按钮充当回车键单击
I'm showing it using jQuery, the principle is the same - add a listener to the space key press, prevent default behaviour and call the function you'd like to use -
$(window).keypress(function (e) {
if (e.keyCode === 0 || e.keyCode === 32) {
e.preventDefault()
console.log('space pressed') // here comes your logic
}
});
You can enable / disable the key listener as you want, for exemple when an input is focused.
Do like this
var input = document.getElementById('input'); input.addEventListener('focus', function(){ disableSpace(false); }); input.addEventListener('blur', function(){ disableSpace(true); }); function disableSpace(enable){ $(window).keypress(function(e) { if (!enable) return true; if (e.keyCode === 0 || e.keyCode === 32) { e.preventDefault() console.log('space pressed'); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="input" type="text" >
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.