我有3个div。其中2个在聚焦时会改变颜色。当其中两个div聚焦时,还可以对另一个div执行操作吗?
div {
border: 1px solid;
margin: 5px;
width: 300px;
height: 50px;
padding: 2px;
}
.myClass:focus {
background-color: yellow;
outline: none;
}
<div class="myClass" tabindex="-1">
Focus me!
</div>
<div class="myClass" tabindex="-1">
You can focus me too!
</div>
<hr />
<div class="anotherClass">
I cannot be focused, but want to change my color, when one of the other divs above me get focused.
</div>
因此,当2个上部div中的1个聚焦时,我希望底部的第3个div改变其颜色。
您可以在这里查看:https://jsfiddle.net/ogpvvwtg/
答案 0 :(得分:6)
当然,您可以使用general sibling selector ~
.myClass:focus ~ .anotherClass {
background-color: red;
outline: none;
}
div {
border: 1px solid;
margin: 5px;
width: 300px;
height: 50px;
padding: 2px;
}
.myClass:focus {
background-color: yellow;
outline: none;
}
.myClass:focus ~ .anotherClass {
background-color: red;
outline: none;
}
<div class="myClass" tabindex="-1">
Focus me!
</div>
<div class="myClass" tabindex="-1">
You can focus me too!
</div>
<hr />
<div class="anotherClass">
I cannot be focused, but want to change my color, when one of the other divs above me get focused.
</div>
答案 1 :(得分:1)
你可以通过一些javascript来做到这一点,这可以让你更好地控制你想要着色的东西。
colorDiv3 = function() {
window.document.getElementById("div3").style.backgroundColor = "lightGreen";
}
div {
border: 1px solid;
margin: 5px;
width: 300px;
height: 50px;
padding: 2px;
}
.myClass:focus {
background-color: yellow;
outline: none;
}
<div class="myClass" tabindex="-1" onFocus="colorDiv3()">
Focus me!
</div>
<div class="myClass" tabindex="-1" onFocus="colorDiv3()">
You can focus me too!
</div>
<hr />
<div id="div3" class="anotherClass">
I cannot be focused, but want to change my color, when one of the other divs above me get focused.
</div>
答案 2 :(得分:0)
您也可以使用JavaScript完成此操作:
首先给出divs ID:
<div id="topDiv" class="myClass" tabindex="-1">
等...
然后你可以找到它们:
var top_div = document.getElementById('top_div');
var middle_div = document.getElementById('middle_div');
var bottom_div = document.getElementById('bottom_div');
为对象分配事件侦听器。这允许您在聚焦元素时调用函数:
top_div.addEventListener("focus", changeBottomDivColor);
middle_div.addEventListener("focus", changeBottomDivColor);
最后,实际改变颜色的功能:
function changeBottomDivColor() {
bottom_div.style.backgroundColor = "red";
}