簡體   English   中英

在輸入字段中輸入文本時,是否可以更改div的背景?

[英]Is there a way to change the background of a div when text is entered into an input field?

我有下面的代碼,我希望每次有人在輸入字段中輸入/鍵入文本時,使用“ target_bg”類強制div的背景將其顏色從紅色(默認)更改為綠色。

<div class="target_bg"></div>
<input placeholder="Search for Restaurants..." 
class="search_field" name="" type="text">

我花了很多時間尋找解決方案,但我只找到了如何更改輸入字段本身的背景。

如果使用jQuery:

$('.search_field').on('input', function() {
   $('.target-bg').css('background-color','green');
});

這是使用普通javascript的解決方案

 var bgElement = document.querySelector('.target_bg'); var input = document.querySelector('.search_field'); input.oninput = function() { bgElement.style.background = 'green'; }; 
 .target_bg { width: 50px; height: 50px; background: red; } 
 <div class="target_bg"></div> <input placeholder="Search for Restaurants..." class="search_field" name="" type="text"> 

暫無
暫無

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

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