简体   繁体   English

我的textarea文本没有使用javascript样式化到CSS

[英]My textarea text isn't styling the way that i would like it to CSS with javascript

I would like the text in the textarea to start off grey and turn to black after text has been entered. 我希望文本区域中的文本从灰色开始,并在输入文本后变为黑色。 the text wont start off grey but if i click on it then off then on again it will be grey. 文本不会以灰色开始,但是如果我单击它,然后再关闭,则它将再次是灰色。

HTML code HTML代码

<li class="message">
<textarea name="message" id="message_input" rows="4" cols="25" maxlength="200"
            onfocus="if(this.value=='Add additional information here!') 
            {this.value='';this.style.color='#000';}" 
            onblur="if(this.value=='') {
            this.value='Add additional information here!';this.style.color='#999';}"
            >Add additional information here!</textarea>
</li>

CSS code CSS代码

li.message {
    position: absolute;
    top:255px;
    left: 150px;
    color: #999;
}

Style the textbox, not the LI 设置文本框的样式,而不是LI

li.message textarea {     
    color: #999;
}

You could utilize jQuery to more easily manipulate the DOM, see this JsFiddle example where I am changing the text color depending on focus() and blur(). 您可以利用jQuery更轻松地操作DOM,请参见此JsFiddle示例,在该示例中,我根据focus()和blur()更改了文本颜色。

<li class="message">
    <textarea name="message" id="message_input" rows="4" cols="25" maxlength="200">Add additional information here!</textarea>
</li>

li.message {
    position: absolute;
    top:255px;
    left: 150px;
    list-style: none;
}

$(document).ready(function(){
    $('#message_input').focus(function(){ $(this).css('color','gray'); });
    $('#message_input').blur(function(){ $(this).css('color','black'); });
});

Try and avoid inline javascript declarations. 尝试避免内联javascript声明。 It is also better to use classes to manage your style changes. 最好使用类来管理样式更改。 Even this could be improved upon as I would like to see the default value stored and checked instead of checking the string each time. 甚至可以对此进行改进,因为我希望查看并检查默认值,而不是每次都检查字符串。 classList is not supported by IE7, but there are workaround if you must support it. IE7不支持classList ,但是如果必须支持,则可以采用解决方法。

http://jsfiddle.net/bTRgz/1/ http://jsfiddle.net/bTRgz/1/

var textarea = document.getElementById('message_input');
textarea.onfocus = function() {
    if (this.value == 'Add additional information here!') {
        this.value = '';
        this.classList.add('active');
    }
};

textarea.onblur = function() {
    if (this.value == '') {
        this.value = 'Add additional information here!';
        this.classList.remove('active');
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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