把注意力集中在按下" esc"键

时间:2016-10-21 13:14:53

标签: javascript html css html5 css3

当用户点击搜索框时,用户会看到一个"闪烁的光标"在搜索框内。

我想,当用户按下 Esc 键时,"闪烁光标"应该离开搜索框并从搜索框中聚焦。

我需要JavaScript代码来执行此操作。

input[type=text] {
    width: 130px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon .ng');
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
    -webkit-transition: width 0 .s ease-in-out;
    transition: width 0 .s ease-in-out;
}

input[type=text] :ocus {
    width: 100%;
}

<p>Animated search form :/p>

<form>
  <input type="text" name="search" placeholder="Search .">
</form>

2 个答案:

答案 0 :(得分:2)

在&#34; esc&#34;时使用InteractiveCanvas按下工作得很好,在哪里&#34;搜索&#34;是给搜索框的id。

&#13;
&#13;
document.getElementById("search").blur()
&#13;
document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {//27 is the code for escape
        document.getElementById("search").blur(); 
    }
};
&#13;
input[type=text] {
    width: 130px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
    width: 100%;
}
&#13;
&#13;
&#13;

答案 1 :(得分:1)

既然你提到了jQuery - 这就是解决方案。

$('input[type=text]').keyup(function(e) {
  if (e.keyCode === 27) $(this).blur(); 
});
input[type=text] {
    width: 130px;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px;
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
    -webkit-transition: width 0.4s ease-in-out;
    transition: width 0.4s ease-in-out;
}

input[type=text]:focus {
    width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Animated search form:</p>

<form>
  <input type="text" name="search" placeholder="Search..">
</form>