2

我对 JavaScript 完全陌生,想修改表单的文本区域(由外部脚本生成),如下所示:

1.) 开始时的文本区域:用颜色 'rgb(136, 136, 136)' 标记为 'Your message here'

2.) Textarea on focus:标签被移除,颜色设置为 'rgb(0, 0, 0)'

3.) Textarea on blur: 用户输入的颜色设置为 'rgb(136, 136, 136)'; 如果没有输入,标签会以颜色 'rgb(136, 136, 136)' 重新出现

我已经尝试过

var foo = document.getElementById('HCB_textarea');
foo.innerHTML = 'Your message here';
foo.style.color = 'rgb(136, 136, 136)';
foo.onfocus = do something;
foo.onblur = do something;

但没有做对。TIA

4

2 回答 2

1

假设您的“标签”不是标签 HTML 元素,而是您的示例似乎建议的 textrea 中的默认文本,请尝试以下操作:

var foo = document.getElementById('HCB_textarea');
var defaultText = 'Your message here';
foo.value = defaultText;
foo.style.color = '#888';
foo.onfocus = function(){
    foo.style.color = '#000';
    if ( foo.value == defaultText ) {
        foo.value = '';
    }
};
foo.onblur = function(){
    foo.style.color = '#888';
    if ( foo.value == '' ) {
        foo.value = defaultText;
    }

};
于 2010-04-13T14:42:02.977 回答
1

这看起来和我很接近。你必须为所有的文本区域着色或不着色,如果没有一些疯狂的黑客,你就无法为某些字符着色。

var foo = document.getElementById('HCB_textarea');
var labelVal = 'Your message here'
foo.value = origVal;
foo.style.color = 'rgb(136, 136, 136)';
foo.onfocus = function() {
  if( foo.value == labelVal ) foo.value = "";
  foo.style.color = 'rgb(136, 136, 136)';
}
foo.onblur = function() {
  if( foo.value != "" ) {
    foo.style.color = 'rgb(0, 0, 0)';
  } else {
    foo.value = labelVal;
    foo.style.color = 'rgb(136, 136, 136)';
  }
}
// You should modify this to use your actual form name.
document.forms[0].onsubmit = function() {
  if( foo.value == labelVal ) foo.value = "";
}

编辑- 我修改了代码,因为马里奥指出您的意思是您希望标签位于文本区域内,而不是<label>元素内。

于 2010-04-13T14:43:12.087 回答