Html 关注一个元素会改变另一个元素的 CSS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15727923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:02:26  来源:igfitidea点击:

focusing on an element changes another's CSS

htmlcssfocus

提问by Sami

I want to change an element's color Hdr_nav_search_boxwhen focusing on another element Hdr_nav_search_input. Here are the codes : http://jsfiddle.net/FJAYk/4/I don not see why this is not working.

我想Hdr_nav_search_box在关注另一个元素时更改元素的颜色Hdr_nav_search_input。以下是代码:http: //jsfiddle.net/FJAYk/4/我不明白为什么这不起作用。

<input class="Hdr_nav_search_input" />
<div class="Hdr_nav_search_box" /><span>search for location....</span><i>for example: blah blah</i></div>

-

——

.Hdr_nav_search_box{
padding: 0 5px;
margin: 7.5px 0;
width:300px;
height: 25px;
background: white;
 }
.Hdr_nav_search_input:focus .Hdr_nav_search_box{
color: #d4d4d4;
 }
.Hdr_nav_search_box span,.Hdr_nav_search_box i{
line-height: 25px;
color: gray;
}
.Hdr_nav_search_input{
padding: 0 5px;
margin: 7.5px 0;
border: 0;
z-index: 2;
position: absolute;
width:300px;
height: 25px;
background: transparent;    
}

回答by Daniel Imms

There were a few problems with your styles. Firstly your selector to target the box isn't quite right.

你的风格有一些问题。首先,您定位框的选择器不太正确。

.Hdr_nav_search_input:focus .Hdr_nav_search_box

That is applying selecting all .Hdr_nav_search_boxwhere they are a descendant of .Hdr_nav_search_input. It's actually a sibling so you want to use the next sibling selector +:

这就是应用选择所有.Hdr_nav_search_box它们是.Hdr_nav_search_input. 它实际上是一个兄弟,所以你想使用下一个兄弟选择器+

.Hdr_nav_search_input:focus + .Hdr_nav_search_box


Secondly this selector would be overriding your colour change if it was working.

其次,如果该选择器正常工作,它将覆盖您的颜色更改。

.Hdr_nav_search_box span,.Hdr_nav_search_box i{
    ...
}

You could use simply

你可以简单地使用

.Hdr_nav_search_box {
    ...
}


Here is a demo and the style changes I made to get it working.

这是一个演示以及我为使其正常工作所做的样式更改。

jsFiddle

js小提琴

.Hdr_nav_search_input:focus + .Hdr_nav_search_box {
    color: #F00;
 }
.Hdr_nav_search_box {
    line-height: 25px;
    color: gray;
}