簡體   English   中英

如何在輸入聚焦時設置表單元素的樣式?

[英]How to style a form element when an input is focused?

我有一個類似於下面的結構的表單。 input[type=text]聚焦時,如何使用CSS來設置input[type=submit]元素的樣式?

例如:

<form id="example">
    <input type="text" name="search">
    <input type="submit" value="Search">
</form>

<style>
    #example > input[type="text"]:focus {
        // please style input[type="submit"]
    }
</style>

我正在努力實現這一目標,因為wordpress主題有一個帶有搜索輸入和內聯提交按鈕的搜索表單。 當用戶專注於輸入時,我希望輸入字段和提交按鈕具有相同的邊框顏色更改。

或者,我可以圍繞輸入和提交按鈕設置整個div的樣式,但是當我們關注一個元素時,我們會回到設計另一個元素的問題。

這甚至可以使用CSS3,還是我必須使用javascript函數? (最后一招。)

如果實際代碼中的結構與您發布的內容相同,則可以使用+ (相鄰)選擇器在關注文本輸入時選擇提交按鈕。

這是您正在尋找的選擇器: #example > input[type="text"]:focus + input[type="submit"]

要閱讀有關+選擇器的更多信息,請回答“+”(加號)CSS選擇器是什么意思?“ 以簡短的方式解釋它,甚至涵蓋瀏覽器支持。


這是一個顯示它在行動的片段。 看起來不太漂亮,但做的工作:)

 #example > input[type="text"]:focus + input[type="submit"] { background: gray; } 
 <form id="example"> <input type="text" name="search"> <input type="submit" value="Search"> </form> 

這是一種使用JQuery的方法,請參閱小提琴https://jsfiddle.net/t33rdra6/2/

  $(document).ready(function() {

    $('input').blur(function() {
        $('input[type="submit"]').removeClass("focus")
      })
      .focus(function() {
        $('input[type="submit"]').addClass("focus");
      });
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM