一个元素上的 CSS 事件,改变另一个元素

标签 css hover element

如何使用 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);

DEMO

如果你使用像 jQuery 这样的库,那么它会变得更容易:

$('#one').hover(function(){
    $('#two').css({'opacity': 1})},
function(){
    $('#two').css({'opacity': 0})
});​​

DEMO

关于一个元素上的 CSS 事件,改变另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12459301/

相关文章:

html - 悬停时不显示 css 无法正常工作

jquery - 具有悬停的元素然后单击会删除悬停效果,再次单击会再次添加悬停效果

css 悬停不起作用

c - C 中列表的第一个元素不正确(linux/list.h)

html - CSS Div Min-Height 直到底部页面才适合

css - 使用 CSS3 将圆圈分段

jquery - HTML 数据表 : Table row is going outside

html - 图像在列中垂直居中

python - 检查列表中的元素

xml - org.apache.batik.bridge.BridgeException : null:-1 The attribute "xlink:href" of the element <use> is required