onFocus and onBlur

2019-07-22 00:51发布

问题:

For some reason the onblur and onfocus properties don't work. Am I defining them right?

var replyTxt = document.createElement("input");
    replyTxt.id="replyTxt";
    replyTxt.type="text";
    replyTxt.value="Write a reply";

    replyTxt.onfocus = function(){if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';};
    replyTxt.onblur= function(){if(replyTxt.value=='') replyTxt.value=replyTxt.defaultValue;};

I have also tried putting "function(){if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';}" in quotations

回答1:

The events work - so there may be a problem with your logic...

if(replyTxt.value==replyTxt.defaultValue) replyTxt.value='';

Where do you set replyTxt.defaultValue? In your example, you don't - so the logic will never fire. Try this...

var replyTxtDefaultText = "Write a reply";
var replyTxt = document.createElement("input");
    replyTxt.id="replyTxt";
    replyTxt.type="text";
    replyTxt.value=replyTxtDefaultText;

    replyTxt.onfocus = function(){if(replyTxt.value==replyTxtDefaultText) replyTxt.value='';};
    replyTxt.onblur= function(){if(replyTxt.value=='') replyTxt.value=replyTxtDefaultText;};


回答2:

Just a hint: try replacing replyTxt with this in your event functions.



回答3:

try setAttribute. more information about function take a look this link

var replyTxt = document.createElement("input");
replyTxt.setAttribute('onFocus', 'focusFunction()');

function focusFunction()
{
   if(replyTxt.value==replyTxtDefaultText) 
      replyTxt.value='';
}


回答4:

And make sure you append it to something.

<form id="x">
</form>
<script>
window.onload=function() {
  var replyTxt = document.createElement("input");
  replyTxt.id="replyTxt";
  replyTxt.type="text";
  replyTxt.value=replyTxt.defaultValue="Write a reply";
  replyTxt.onfocus = function(){if(this.value==this.defaultValue) this.value='';};
  replyTxt.onblur= function(){if(this.value=='') this.value=this.defaultValue;};

  document.getElementById('x').appendChild(replyTxt);
}
</script>


回答5:

Actually I was working on a similar problem as a homework and I found out that is better to clear the field as soon as the mouse lands on the field rather than making a comparison if left untouched and then clear it.