gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:09:53 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com