簡體   English   中英

在字段中輸入文本更改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>

我建議使用類而不是更改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*/

您似乎定位了錯誤的元素

您的選擇器應該是

$(this).parent('#colorchange')

$(this).parent()指向div id="colorchange">

您正在嘗試再次尋找將搜索其子級的子級

如果要立即反映change ,請使用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');
         }
     });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM