我尝试在点击或关注文本框时更改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>
任何想法?
答案 0 :(得分:0)
要更改文本选择颜色,您只需要CSS。你不能用JavaScript做到这一点,除非有不那么漂亮的黑客(你需要在选择的单词的顶部/下面画一个矩形)。
使用CSS你只需要做(我相信):
#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。
答案 1 :(得分:0)
这是一个使用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';
};