在字段中输入文本更改div的背景颜色(Input text in field change background color of 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>I want to have the div background color change colors only when there is text in the input field and when there is no text there the color doesn't change or it reverts back to the original color. Here is my code so far and it doesn't work.
<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*/I'd suggest using classes instead of changing CSS attributes. This should work
$(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"); } }); });Now add some 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*/更多推荐
发布评论