在字段中输入文本改变div的背景颜色
我只想在输入字段中存在文本时没有文本,并且颜色没有改变或者它恢复为原始的颜色。这是我的代码到目前为止,它不起作用。在字段中输入文本改变div的背景颜色
<script type="text/javascript">
$(document).ready(function() {
$('#inputDatabaseName').change(function() {
$(this).parent().find('#colorchange').css('background-color','#ff0000');
$(this).css('background-color','#ff0000');
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="colorchange">
<input id="inputDatabaseName">
<table id="searchResults"><tr><td>empty</td></tr></table>
</div>
</form>
</body>
我建议使用类而不是改变CSS属性。这应该工作
$(function() {
$('#inputDatabaseName').keypress(function() {
var $this = $(this),
$div = $(this).parent(); // Cache the jQuery selectors to make code faster
if ($this.val().length > 0) {
$div.addClass("hasContent");
} else {
$div.removeClass("hasContent");
}
});
});
现在添加一些CSS:
#colorchange { background-color: white } /* default color */
#colorchange.hasContent { background-color: red } /* updated color */
#colorchange #inputDatabaseName { background-color: white } /* default color */
#colorchange.hasContent #inputDatabaseName { background-color: red } /*updated color*/
你的代码只改变了输入字段的颜色,而不是它所在的div。 – user2607442
您没有提及更新输入字段......我会在几分钟内更新。 – Webberig
非常感谢,做到了。 – user2607442
你似乎瞄准错误的元素
你的选择应该是
$(this).parent('#colorchange')
$(this).parent()
指向div id="colorchange">
而你正试图再次找到它会搜索其子
如果你想立即反映更改使用keyup
事件而不是change
。
另外ID
应该是唯一的页面上。
因此$('#colorchange').css(
应该这样做。
$(document).ready(function() {
$('#inputDatabaseName').keyup(function() {
var $this = $(this);
$colorDiv = $('#colorchange');
defaultColor = 'initial';
// If value is not empty assign a color
// otherwise this will be set to default.
if ($this.val() !== '') {
defaultColor = '#ff0000';
}
$('#colorchange').css('background-color', defaultColor);
$this.css('background-color', defaultColor);
});
});
你可以用这个JavaScript
$('#inputDatabaseName').change(function() {
if($(this).val() ==="") {
$(this).parents('#colorchange').css('backgroundColor','red');}
else {
$(this).parents('#colorchange').css('backgroundColor','green');
}
});
您的JS甚至不似乎是有效的做到这一点。试试jsfiddle.net(jshint) – pmandell
长话短说,你关闭了你的改变功能,但没有你的就绪功能。修复并再试一次。并且在将来,请检查您的错误控制台。 – 2013-08-01 19:24:03