Styling a textarea with JavaScript

非 Y 不嫁゛ 提交于 2019-12-11 03:35:16

问题


I'm absolutely new to JavaScript and would like to modify a textarea of a form (which is generated by an external script) as follows:

1.) Textarea on start: Labeled 'Your message here' in color 'rgb(136, 136, 136)'

2.) Textarea on focus: Label removed and color set to 'rgb(0, 0, 0)'

3.) Textarea on blur: Color of user input set to 'rgb(136, 136, 136)'; if there's no input, label reappears in color 'rgb(136, 136, 136)'

I've experimented around with

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;

but didn't get it right. TIA


回答1:


Presuming by 'label' you don't mean a label HTML element, but instead default text in the textrea as your example seems to suggest, try this:

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

};



回答2:


That looks pretty close to me. You have to color all or none of the textarea, you can't color certain characters without some crazy hacks.

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

EDIT - I modified the code because Mario pointed out that you meant you wanted the label to be inside of the textarea, not a <label> element.



来源:https://stackoverflow.com/questions/2630378/styling-a-textarea-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!