开发者

onFocus and onBlur

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.defa开发者_JS百科ultValue;};

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


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;};


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


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='';
}


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>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜