将焦点集中在按下“escape”上;关键

fixing focus out on pressing a "esc" key

本文关键字:escape 关键 焦点 集中      更新时间:2023-09-26

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

我希望,当用户按下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>

当按下"esc"时使用document.getElementById("search").blur()就可以了,其中"search"是给定给搜索框的id。

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {//27 is the code for escape
        document.getElementById("search").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%;
}
<p>Animated search form:</p>
<form>
  <input id="search" type="text" name="search" placeholder="Search..">
</form>

既然你提到了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>