如何使用 CSS 更改一个元素和另一个元素上的事件?
E.g. <div id="one"> ....., <div id="two">....
<style>
#one:hover
{
changing the visibility of #two...
}
</style>
最佳答案
在您的情况下,您希望更改的元素在您悬停的元素之后,这意味着您的结构如下:
<div id="one"></div>
<!--you could have some elements between them-->
<div id="two"></div>
或喜欢:
<div id="one">
<!--maybe some elements-->
<div id="two"></div>
<!---->
</div>
在第一种情况下(#one
和 #two
是 sibling ,即它们处于同一级别 = 具有相同的父级),您使用 the general sibling combinator ( ~
),像这样:
#one:hover ~ #two { /* style changes */ }
DEMO对于 #one
的情况和 #two
是 sibling 和#one
在 #two
之前在 HTML 中。
在第二种情况下( #two
是 #one
的后代),您使用:
#one:hover #two { /* style changes */ }
DEMO对于 #two
的情况是 #one
的后代.
但是,如果您希望更改之前 #one
的元素在 HTML 中,目前 ( meaning that this could change in the future ) 单独使用 CSS 是不可能的(如果您想知道原因,那么 this article 提供了解释)。
但在这种情况下,当 #two
在 #one
之前在 HTML 中,您可以使用 JavaScript 来完成。例如,如果 #two
的不透明度最初是 0
, 然后你可以把它改成 1
悬停时 #one
使用:
var one = document.getElementById('one'),
two = document.getElementById('two');
one.addEventListener('mouseover', function(){
two.style.opacity = 1;
}, true);
one.addEventListener('mouseout', function(){
two.style.opacity = 0;
}, true);
如果你使用像 jQuery 这样的库,那么它会变得更容易:
$('#one').hover(function(){
$('#two').css({'opacity': 1})},
function(){
$('#two').css({'opacity': 0})
});
关于一个元素上的 CSS 事件,改变另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12459301/