javascript給input設定預設提示例子

來源:互聯網
上載者:User

例子

 代碼如下 複製代碼

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" class="input" onfocus="myFocus(this)" onblur="myBlur(this)" value="11">
<input type="text" class="input" onfocus="myFocus(this)" onblur="myBlur(this)" value="22">
</body>
</html>
<script>
function myFocus(element){
if (element.value == element.defaultValue){
   element.focus();
   element.value = '';
}
    }
    function myBlur(element){
    if (element.value == ''){
  element.blur();
  element.value = element.defaultValue;
    }
}
</script>

補充:

onFocus事件就是當游標落在文字框中時發生的事件。

onBlur事件是游標失去焦點時發生的事件。

支援該事件的js對象

button, checkbox, fileUpload, layer, frame, password, radio, reset, select, submit,
text, textarea, window


當然我們也可以使用jquery來實現了,方法更簡單並且代碼也簡潔許多少。

 代碼如下 複製代碼

$("#id").focus(function(){
             ……
});

與

$("input").blur(function(){
  $("input").css("background-color","#D6D6FF");
});

例子

 代碼如下 複製代碼

html

<input name="q" type="text" class="you" id="xf_search"  value="11111">

jquery代碼

<script type="text/javascript">
(function (){ $("#xf_search").focus(function (){(this.value=='11111')?this.value='':false}); $("#xf_search").blur(function (){(this.value=='')?this.value='11111':false}); }());
</script>


方法可以實現我們不在html表單上加js代碼這個從最佳化方面來講是有很大的提升哦

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.