2017-09-24 28 views
1

我偶然發現這種情況:當輸入字段的寬度通過按鈕進行控制時,自動對焦不起作用。專注於點擊無法正常工作或因爲它觸發寬度的動畫落後......HTML5輸入自動對焦不起作用

我懷疑一個愚蠢的錯誤層次的地方,所以這裏是一個codepen來告訴你我所做的:https://codepen.io/anon/pen/qPqXdp

對不起,基本的麻煩恐怕......

.center { 
 
    margin: 0 auto; 
 
    width: 700px; 
 
} 
 

 
.search-wrap { 
 
    position: relative; 
 
} 
 

 
.search-button { 
 
    width: 50px; 
 
    height: 50px; 
 
    position: absolute; 
 
    right: 0; 
 
} 
 

 
.search-form { 
 
    height: 51px; 
 
    width: 0; 
 
    position: absolute; 
 
    right: 50px; 
 
    top: 0; 
 
    -webkit-transition: width 400ms ease; 
 
    transition: width 400ms ease; 
 
} 
 

 
.search-form .search-field { 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 

 
.search-button:focus+.search-form { 
 
    width: 650px; 
 
    right: 50px; 
 
}
<div class="center"> 
 
    <div class="search-wrap"> 
 
    <button class="search-button">?</button> 
 
    <form class="search-form"> 
 
     <label> 
 
      <input type="search" class="search-field" autofocus/> 
 
     </label> 
 
    </form> 
 
    </div> 
 
</div>

回答

0

autofocus財產在你的榜樣正常工作。問題是,當您單擊該按鈕時,焦點將從input更改爲button您一次只能關注一個元素,因此無法按照您的要求進行操作。然而,你可以使用:checked僞類來實現同樣的結果:

.center { 
 
    margin: 0 auto; 
 
    width: 700px; 
 
} 
 

 
.search-wrap { 
 
    position: relative; 
 
} 
 

 
.change-width { 
 
    width: 50px; 
 
    height: 50px; 
 
    position: absolute; 
 
    right: -10px; 
 
} 
 

 
.search-form { 
 
    height: 51px; 
 
    width: 0; 
 
    position: absolute; 
 
    right: 50px; 
 
    top: 0; 
 
    -webkit-transition: width 400ms ease; 
 
    transition: width 400ms ease; 
 
} 
 

 
.search-form .search-field { 
 
    height: 100%; 
 
    width: 100%; 
 
} 
 

 
#change:checked + .search-form { 
 
    width: 650px; 
 
    right: 50px; 
 
} 
 

 
#change { 
 
\t display: none; 
 
}
<div class="center"> 
 
    <div class="search-wrap"> 
 
    <label for="change" class="change-width">?</label> 
 
    <input id="change" type="checkbox"> 
 
    <form class="search-form"> 
 
     \t <label> 
 
      \t <input type="search" class="search-field" id="input"> 
 
     \t </label> 
 
    </form> 
 
    </div> 
 
</div>

現在你可以專注的onclick。 autofocus仍然無法工作,因爲點擊頁面上的任何位置(在這種情況下,在label)將取消它。