如何解决javascript高亮显示
| 我尝试使div颜色在单击或聚焦于文本框时发生更改,因此我执行此js函数,但它更改了文本框颜色而不是其div<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\">
<head>
<title>test</title>
<style type=\"text/css\">
/* This is the CSS class to use when no focus is on the input control */
.input_text
{
border:1px solid #c0c0c0;
padding:4px;
font-size:14px;
color:#000000;
background-color:#ffffff;
}
/* This is the CSS class to use when the control has focus */
.input_text:focus,input.input_text_focus
{
border-color:#646464;
background-color:#ffffc0;
}
</style>
<script type=\"text/javascript\">
// creates a function to set the css class name of input controls when they
// receive or lose focus.
setAspnetTextFocus = function() {
// CSS class name to use when no focus is on the input control
var classBlur = \'input_text\';
// CSS class name to use when the input control has focus
var classFocus = \'input_text_focus\';
// get all of the input tags on the page
var inputElements = document.getElementsByTagName(\'input\');
for (var i = 0; i < inputElements.length; i++) {
inputElements[i].onfocus = function() {
if (this.className == \'input_text\') {
this.className += \' \' + classFocus;
}
}
// add the onblur event and set it to remove the on focused CSS class when it loses focus
inputElements[i].onblur = function() {
this.className = this.className.replace(new RegExp(\' \' + classFocus + \'\\\\b\'),\'\');
}
}
}
// attach this event on load of the page
if (window.attachEvent) window.attachEvent(\'onload\',setAspnetTextFocus);
</script>
</head>
<body>
<div class=\"input_text\" >
<input type=\"text\" id=\"TextBox1\" class=\"input_text\" />
</div>
</body>
</html>
有任何想法吗?
解决方法
要更改文本,请选择颜色,您只需要CSS。您将无法使用JavaScript进行操作,除非没有那么漂亮的技巧(您需要在选择的单词的上方/下方绘制一个矩形...)
使用CSS tho,您只需要做(我相信):
#TextBox1::selection {
background: #ffb7b7; /* Safari */
}
#TextBox1::-moz-selection {
background: #ffb7b7; /* Firefox */
}
资料来源:http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
只是附带说明,以防万一,这不是W3C验证的CSS。
,这是一个使用JQuery的jsfiddle,它将满足我的要求:http://jsfiddle.net/pthurlow/GG6Te/
这是纯香草JS:http://jsfiddle.net/FSZZU/
来自jsfiddle的编辑代码:
html
<div class=\"input_text\">
<input type=\"text\" id=\"TextBox1\" class=\"input_text\" />
</div>
脚本
document.getElementById(\'TextBox1\').onfocus = function() {
this.parentNode.className = \'input_text focus_text\';
};
document.getElementById(\'TextBox1\').onblur = function() {
this.parentNode.className = \'input_text\';
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。