admin管理员组

文章数量:1336106

In render,

 <div id="container" tabindex="0">
    <input id = "input" type="text" />
  </div>

In css,

#container::focus{
 background-color: "red"
}

I need to make the bg-clr to be fixed in the div when focusing the input field.

In render,

 <div id="container" tabindex="0">
    <input id = "input" type="text" />
  </div>

In css,

#container::focus{
 background-color: "red"
}

I need to make the bg-clr to be fixed in the div when focusing the input field.

Share Improve this question asked Oct 29, 2020 at 7:12 Barry AllenBarry Allen 91 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

Try using :focus-within CSS pseudo-class

The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus.

#container:focus-within {
  background-color: red;
}

#container {
  padding: 30px;
}
<div id="container" tabindex="0">
  <input id="input" type="text" />
</div>

Note: if you don't want to focus div#container directly remove tabindex

What are you trying to achieve isn't possible by css. You need use JavaScript focus and blur event listeners on the input to change the background color of div:

document.querySelector('#input').addEventListener('focus', function(e) {
    e.target.closest("#container").classList.add('focus');
})
document.querySelector('#input').addEventListener('blur', function(e) {
    e.target.closest("#container").classList.remove('focus');
})

CSS:

#container.focus{
 background-color: "red"
}

You'll need to add an onfocus event to the element then

 <div id="container" tabindex="0">
    <input id = "input" type="text" onfocus="myFunction(this)" />

<script>
function myFunction(item) {
    item.style.backgroundColor = 'red';
}
</script>

See this page for more info: https://www.w3schools./jsref/event_onfocus.asp

If you are ready to use the JavaScript, this one can be the one solution. Based on the requirement you can se the color into Focus and Blur event.

$(document).on('focus','.input', function() {
$("#container").css("background-color","black");
})

$(document).on('blur','.input', function() {
$("#container").css("background-color", "white");
})
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
    <input class="input" id="input" type="text" />
  </div>

本文标签: javascriptHow to change the background color of the div while focusing the text Input fieldStack Overflow