键盘监听

Js Keyboard listening

本文关键字:监听 键盘      更新时间:2023-09-26

我的目标是当你键入搜索栏会弹出下面的代码是工作的,但我有一个问题,而键入不同的输入,例如评论输入js听,并打开搜索栏。是否有可能当我已经在一个不同的输入字段,搜索将不会弹出并显示。

<style>
#searchBar { display: none;    -webkit-transition: width 2s; /* Safari */ transition: width 2s;}
.search { width: 250px; height: 20px; }
</style>
<script>
window.onload = function() {
    var listen = /^[a-z0-9]+$/i;
    var searchInput = document.getElementById('searchInput');
    var searchBar = document.getElementById('searchBar');
    if ( window.addEventListener )
        window.addEventListener( 'keyup', insertKey, false);
    function insertKey( e ) {
        // Get the character from e.keyCode
        var key = String.fromCharCode( e.keyCode ).toLowerCase(); 
        // Match the character
        if( key.match(listen) ) {
            // Change display: none; to display: block;
            searchBar.style.display = "block";
            // Append every new character
            searchInput.value += key;
            // Focus on input
            searchInput.focus();
            // Since you focused on the input you don't need to listen for keyup anymore.
            window.removeEventListener( 'keyup', insertKey );
            // I didn't tested with jQuery
            // $('#searchBar').fadeIn();
            // $('#searchBar input').append(keys);
            // $('#searchBar input').focus();
        }
    }
};
</script>

当您为keyup事件添加一个事件侦听器到window时,它将在检测到keyup时触发,无论它来自何处。你对你正在听的事件没有足够的歧视。

一种解决方案是将事件侦听器直接添加到input元素中,这样来自一个元素的keyup就不会触发另一个元素的侦听器:

document.getElementById("searchInput").addEventListener("keyup", searchInputKeyHandler);
document.getElementById("commentInput").addEventListener("keyup", commentInputKeyHandler);
// etc.

这工作,但有点奇怪。如果您所做的只是监听用户在input HTML元素中键入的内容,那么更好的监听事件是input,它会在input元素的值发生变化时触发。

document.getElementById("searchInput").addEventListener("input", searchInputKeyHandler);
document.getElementById("commentInput").addEventListener("input", commentInputKeyHandler);
// etc.

一些元素也可以监听change事件;做一些研究,看看什么事件最适合你的用例。