Highlight text in textarea
I need to hightlight some of the text inside the a <textarea>开发者_StackOverflow中文版;
field using CSS. The text should to be highlighted by default.
I have a normal <textarea>
where the user types something. I need to set the background-color
just for specific text.
You need to use two separate layers. One to display the textarea text and one to show the highlighting. You'll require js, css and html. Ignore the nay-sayers. Coding is about finding solutions. People whom tell you there isn't one, usually aren't coders, they are designers.
I presume you mean having the text selected so it can be removed when the user starts typing or copied to the clipboard. You cannot accomplish such thing with CSS: you need to use JavaScript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript"><!--
window.onload = function(){
var t = document.getElementsByTagName("textarea");
for(var i=0, len=t.length; i<len; i++){
t[i].select();
}
}
//--></script>
</head>
<body>
<textarea>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea>
</body>
</html>
Since you can only have one selected item at a time, it's probably more interesting to select text on focus:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript"><!--
window.onload = function(){
var t = document.getElementsByTagName("textarea");
for(var i=0, len=t.length; i<len; i++){
t[i].onfocus = function(e){
e.target.select();
}
}
}
//--></script>
</head>
<body>
<textarea>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea>
<textarea>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
</body>
</html>
Disclaimer: this sample code is not tested and probably buggy.
Update
Do you mean this?
textarea{
background-color: #FFEFC6;
}
You can't do this in HTML/CSS. Textarea is a block level element and the text inside would need to be wrapped in an inline level element to give it separate highlighting. Try to hack something out from a trimmed down simple WYSIWYG like http://code.google.com/p/jwysiwyg/
精彩评论