文字框input聚焦失焦樣式實現代碼_javascript技巧

來源:互聯網
上載者:User
首先用css的偽類:focus可以改變。

文字框的 html代碼假設如下:
複製代碼 代碼如下:

<dl>
<dt>Name: <dt>
<dd><input type="text" /></dd>
<dt>Password: <dt>
<dd><input type="password" /></dd>
<dt>Textarea: <dt>
<dd><textarea></textarea></dd>
</dl>


css 代碼這樣寫:

input[type="text"]:focus, input[type="password"]:focus, textarea:focus { border: 1px solid #f00; background: #ccc; }
分別列出了文字框、密碼框、還有段落框這三個input框的聚焦時候的樣式。加上個紅色的邊框和灰色的背 景。

現在就這麼簡單的解決了嗎?用瀏覽器(Firefox, Safari, IE7)來測試,一切ok,不過不支援IE6.

想 讓IE6也是一樣漂亮的效果只能藉助接js了,這裡我用jquery給大家做一個效果。
複製代碼 代碼如下:

$(document).ready(function(){
$("input[@type='text'], input[@type='password'], textarea").focus( function(){ $(this). css({background:"#ccc", border:"1px solid #f00"})} );
});

jquery做起來是不是也很簡單,感覺和css的書寫方式差不多吧!

這隻是聚焦狀 態,jquery失焦狀態是要你給出指示的,很傻很天真,它自己不會變回來,那就在給加上失焦狀態。
複製代碼 代碼如下:

$(document).ready(function(){
$("input[@type='text'], input[@type='password'], textarea").focus(function(){$(this).css({background:"#ccc", border:"1px solid #f00"})}).blur(function(){$(this).css({background: “#FFF”, border: “1px solid #ccc”})});
})

失焦以後背景邊成白色,邊框變成灰色。

當然你也可以用 jquery的addClass和removeClass來簡化代碼:
複製代碼 代碼如下:

$(document).ready(function(){
$("input[@type='text'], input[@type='password'], textarea").focus(function(){$(this).addClass("focus")}).blur(function(){$(this).removeClass("focus")});
})

先 給input框給個預設樣式,聚焦的時候用addClass加上css“focus”,失焦的時候在用 removeClass去掉css“focus”。

一切搞定了!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.