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 badges4 Answers
Reset to default 7Try 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>
版权声明:本文标题:javascript - How to change the background color of the div while focusing the text Input field? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742365330a2461164.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论