当有人开始输入(数字或字母)时,我想要一个搜索栏出现,它应该采用用户在其中写入的字母表,即我希望它自动聚焦于该字段。
到目前为止,我有这个......
if (window.addEventListener) {
var keys = [], listen= /^([0-9]|[a-z])\i$/ ;
window.addEventListener("keydown", function(e){
keys.push(e.keyCode);
if(keys.match(listen))
{
$('#searchBar').fadeIn();
$('#searchBar input').text(keys);
$('#searchBar input').focus();
keys = [];
}
},true);
}
我希望输入的第一个字符也在字段中显示。 TY。
答案 0 :(得分:1)
希望这适合你。如果您更喜欢jQuery,则需要进行微小的更改。
<style>
#searchBar { display: none; }
.search { width: 250px; height: 20px; }
</style>
<div id="searchBar">
Search Here: <input type="search" id="searchInput" class="search" />
</div>
<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>
答案 1 :(得分:0)
var listen= /^([0-9]|[a-z])\i$/;
var key = [];
window.addEventListener('keydown', function (e) {
keys.push(e.keyCode);
if(keys.match(listen)) {
$('#searchBar').fadeIn();
$('#searchBar input').append(keys);
$('#searchBar input').focus();
keys = [];
}
});