Html 如何使用 CSS class/id 更改其他类的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20522173/
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-28 22:26:04  来源:igfitidea点击:

How to use CSS class/id to change other classes attributes?

cssclasshtmlhover

提问by Nikolas

So I want to :hover on an element and I want the hovering to change an attribute of another class. How do I do it? I want to hover on to a button and it to change other div's display to display: block. I use only HTML and CSS.

所以我想:悬停在一个元素上,我希望悬停改变另一个类的属性。我该怎么做?我想将鼠标悬停在一个按钮上,它将其他 div 的显示更改为显示:块。我只使用 HTML 和 CSS。

回答by wouthoekstra

You are limited by css, but there are possibilities with css selectors. I've made you a jsfiddle with a possible solution:

您受到 css 的限制,但 css 选择器有可能。我已经让你成为一个可能的解决方案的 jsfiddle:

http://jsfiddle.net/6rT3Q/

http://jsfiddle.net/6rT3Q/

CSS:

CSS:

.item1:hover ~ .item3 {
    background-color: red;
}

HTML

HTML

<div class="item1">
    Hoverable item
</div>

<div class="item2">
    Dummy item
</div>

<div class="item3">
    Item to change
</div>

Here the ~tells to look for succeeding elements. If you want the immediate next element you can use +.

这里~告诉寻找后续元素。如果您想要紧邻的下一个元素,您可以使用+.

More info about selectors:

关于选择器的更多信息:

http://www.w3.org/TR/2001/CR-css3-selectors-20011113/

http://www.w3.org/TR/2001/CR-css3-selectors-20011113/

回答by jbenjohnson

Without using JS, you can change a child node of the element being hovered. For example if you had:

在不使用 JS 的情况下,您可以更改悬停元素的子节点。例如,如果您有:

<div class="container">
    <div class="box">Content</div>
</div>

You could use the below code to change the .box properties:

您可以使用以下代码更改 .box 属性:

.container:hover .box

回答by mumush

For this you would use Javascript. For example with jQuery you could do:

为此,您将使用 Javascript。例如使用 jQuery,您可以执行以下操作:

$( "#hoveredElement" ).mouseover(function() {
   $( "#otherDiv" ).css("display", "block"); //or just use .show() if it is
                                             //initially hidden
});

回答by Hanady

You can use javascriptfor this. Put your button in a div and use the following:

您可以javascript为此使用。将您的按钮放在 div 中并使用以下内容:

document.getElementById("buttonDiv").onmouseover = function() {
    document.getElementById["divToHide"].style.display = "block";
};