简体   繁体   English

如何使用onfocus?

[英]How to operate with onfocus?

I have a textbox. 我有一个文本框。

Now when the page is opened i want the textbox to have a default value.Once he click on the textbox the value should disappear and again when he removes his cursor from the text box ,the old value should come back. 现在当打开页面时,我希望文本框具有默认值。一旦他点击文本框,该值就会消失,当他从文本框中移除光标时,旧值应该会返回。

So how do i do this ? 那我该怎么做?

Thanks 谢谢

Add a specific class to all textboxes on the page that you want to have this functionality. 将特定类添加到要具有此功能的页面上的所有文本框中。

Then, use this code to apply the functionality to the elements that have the class: 然后,使用此代码将功能应用于具有该类的元素:

window.onload = function() {
   var elements = document.querySelectorAll('.yourClassName');
   for(var i = 0, j = elements.length; i < j; i++) {
      var element = elements[i]; 
      element.onfocus = function() {
         this.value = '';
         this.style.color = 'black';
      };
      element.onblur = function() {
          if(this.value == '') {
             this.value = this.getAttribute('defaultValue');
             this.style.color = 'grey';
          }
      };
      element.onblur();
   }
};
​

Working example: http://jsfiddle.net/6TmGA/1/ 工作示例: http//jsfiddle.net/6TmGA/1/

Can you use jQuery? 你能用jQuery吗?

If you can there are a lot of plugins that will help with this. 如果你能有很多插件可以帮助解决这个问题。

such as; 如;

http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/ http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/

<script language="JavaScript">
    function setFocus() {

           document.getElementById('username').focus();

    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM