简体   繁体   中英

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

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

只是一个提示:尝试在您的事件函数中用this替换replyTxt

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>

实际上,我正在研究与家庭作业类似的问题,我发现最好在鼠标落在场地上后立即清除场地,而不是在保持不变的情况下进行比较然后清除它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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