简体   繁体   English

CSS悬停不会影响其他元素

[英]CSS hover does not affect on other element

CSS :hover works when I use it for it's own element, but when i tried to affect another element, it had no effect. 当我将CSS :hover用于它自己的元素时,它可以工作,但是当我尝试影响另一个元素时,它没有任何作用。

For example, when I hover this button, the hidden links should appear, but they do not. 例如,当我将鼠标悬停在该按钮上时,应显示隐藏的链接,但不会显示。

 .dropdown { position: relative; display: inline-block; border: 1px solid black; width: 200px; } .dropbutton { width: 100%; height: 60px; color: white; background: #017678; border: none; } .dropcontent a { color: black; text-align: center; line-height: 40px; text-decoration: none; height: 40px; background-color: #DDD; border-width: 0 0 1px 0; border-style: solid; border-color: #9fa0a8; display: none; } a:last-of-type { border: none; } .dropbutton:hover .dropcontent { display: block; } 
 <div class="dropdown"> <button class="dropbutton">SHOW CONTENT</button> <div class="dropcontent"> <a href="#">c1</a> <a href="#">c2</a> <a href="#">c3</a> </div> </div> 

A space is a descendant combinator . 空间是后代组合器 It targets descendants, but the div is not a descendant of the button, it is a sibling. 它以后代为目标,但div不是按钮的后代,它是同级。

You need to use the adjacent sibling combinator instead: a plus sign. 您需要使用相邻的同级组合器 :加号。

You also need to target the links (which are descendants of .dropcontent so you should use a descendant combinator there) since it is those which you have set display: none on and not the div. 您还需要定位链接(这些链接是.dropcontent后代,因此您应在此使用后代组合器),因为这些链接已设置为display: none ,而不显示div。

.dropbutton:hover + .dropcontent a {

I'd move the display: none; 我要移动display: none; to the .dropcontent itself - as it now pertains to its anchors, that is, links, and as such, neither current answer would work -, then use .dropcontent本身-因为它现在与它的锚点(即链接)有关,因此,当前答案都不起作用-然后使用

.dropbutton:hover + .dropcontent
{
    display: block;
}

But you must not add anything between dropbutton and dropcontent afterwards, or it will not work any more. 但是您之后不得在dropbutton和dropcontent之间添加任何内容,否则它将不再起作用。

Are you using Javascript to do this? 您是否正在使用Javascript执行此操作?

var button = document.getElementsByClassName('.dropbutton')[0],
    menuContent = docuemnt.getElementsByClassName('.dropcontent')[0];

button.onmouseover = function(event) {
    menuContent.style.display['block'];
}
button.onmouseout = function(event) {
    menuContent.style.display['none'];
}

With a slight change to your CSS: .dropbutton should have display: none , and you should remove the display: none from .dropcontent a 稍微更改一下CSS: .dropbutton应该具有display: none ,并且您应该从.dropcontent a删除display: none

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM