显示搜索栏并在按键后关注它

时间:2016-05-04 13:00:32

标签: jquery html css css3

我希望在用户按下" R"时显示搜索栏。按键,搜索栏也应该在按键后聚焦,这里是小提琴:



buttonKeyAllowed = true;

function disparitionMenu() 
/* this function is used to show the searchbar */
{
    var input = jQuery("#mod-search-searchword");
    input[0].selectionStart = input[0].selectionEnd = input.val().length;
    jQuery("#menu-search").css("display", "inline-block");
}
    
/*-- key events --*/


jQuery(document).keyup(function() {
  buttonKeyAllowed = true;
});


jQuery(document).focus(function(e) { 
  buttonKeyAllowed = true;
});


jQuery(document).keypress(function(e) {		
       
  if (e.repeat != undefined) {
    buttonKeyAllowed = !e.repeat;
  }
  if (!buttonKeyAllowed) 
    return;
  buttonKeyAllowed = false;


  var code = (e.keyCode || e.which);

  if(code == 114) {
    disparitionMenu();
  }
});

#menu-search
{
  display: none;
}

input{
  width: 100px;
  background-color: white;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


  <div id="megamenu">
    <div id="menu-search">
      <input type="text" id="mod-search-searchword" />
    </div>
  </div>
&#13;
&#13;
&#13;

这段代码很好用,但有一个问题:

当用户按下&#34; R&#34;关键时间太长了,&#39; r&#39;写在搜索栏中,我想避免它。

解决此问题的最简洁方法是什么?我不想在函数while(/* is R key down*/){}

之前添加disparitionMenu()循环

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

input.focus();添加到function disparitionMenu()。检查以下代码。

&#13;
&#13;
buttonKeyAllowed = true;

var isVisible = false;

function disparitionMenu()
  /* this function is used to show the searchbar */
  {
    var input = jQuery("#mod-search-searchword");
    input[0].selectionStart = input[0].selectionEnd = input.val().length;
    jQuery("#menu-search").css("display", "inline-block");
    input.focus();
  }

/*-- key events --*/


jQuery(document).keyup(function() {
  buttonKeyAllowed = true;
});

jQuery(document).focus(function(e) {
  buttonKeyAllowed = true;
});

jQuery(document).keypress(function(e) {

  if (e.repeat != undefined) {
    buttonKeyAllowed = !e.repeat;
  }
  if (!buttonKeyAllowed)
    return;
  buttonKeyAllowed = false;


  var code = (e.keyCode || e.which);

  if (code == 114) {
    if (!isVisible) {
      isVisible = true;
      e.preventDefault();
    }
    disparitionMenu();
  }
});
&#13;
#menu-search {
  display: none;
}
input {
  width: 100px;
  background-color: white;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div id="megamenu">
  <div id="menu-search">
    <input type="text" id="mod-search-searchword" />
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

使用readonly输入您的输入

<input type="text" id="mod-search-searchword" readonly="true" />

关于事件onkeyup如果被置于readonly false或将其删除。

jQuery(document).keyup(function(e) {        
    var code = (e.keyCode || e.which);    
  if(code == 82) {
    $('#mod-search-searchword').removeAttr('readonly');
  }
});

也删除事件:) ^