Html 当一个元素悬停时如何影响其他元素

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

How to affect other elements when one element is hovered

htmlcsshover

提问by Trufa

What I want to do is when a certain divis hovered, it'd affect the properties of another div.

我想要做的是当某个人div悬停时,它会影响另一个div.

For example, in this JSFiddle demo, when you hover over #cubeit changes the background-colorbut what I want is that when I hover over #container, #cubeis affected.

例如,在这个 JSFiddle 演示中,当您将鼠标悬停在#cube它上面时会改变,background-color但我想要的是,当我将鼠标悬停在 时#container#cube会受到影响。

div {
  outline: 1px solid red;
}
#container {
  width: 200px;
  height: 30px;
}
#cube {
  width: 30px;
  height: 100%;
  background-color: red;
}
#cube:hover {
  width: 30px;
  height: 100%;
  background-color: blue;
}
<div id="container">

  <div id="cube">
  </div>

</div>

回答by Mike

If the cube is directly inside the container:

如果立方体直接在容器内:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

如果立方体在容器旁边(在容器关闭标签之后)容器:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

如果立方体在容器内的某个地方:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

如果多维数据集是容器的兄弟:

#container:hover ~ #cube { background-color: yellow; }

回答by Emmett

In this particular example, you can use:

在此特定示例中,您可以使用:

#container:hover #cube {
    background-color: yellow;   
}

This example only works since cubeis a child of container. For more complicated scenarios, you'd need to use different CSS, or use JavaScript.

此示例仅适用cubecontainer. 对于更复杂的场景,您需要使用不同的 CSS,或者使用 JavaScript。

回答by Dan Dascalescu

Using the sibling selector is the general solution for styling other elements when hovering over a given one, butit works only if the other elements follow the given one in the DOM. What can we do when the other elements should actually be before the hovered one? Say we want to implement a signal bar rating widget like the one below:

使用同级选择器是将鼠标悬停在给定元素上时为其他元素设置样式的通用解决方案,仅在其他元素跟随 DOM 中的给定元素时才有效。当其他元素实际上应该在悬停元素之前时,我们该怎么办?假设我们要实现一个如下所示的信号栏评级小部件:

Signal bar rating widget

信号栏评级小部件

This can actually be done easily using the CSS flexbox model, by setting flex-directionto reverse, so that the elements are displayed in the opposite order from the one they're in the DOM. The screenshot above is from such a widget, implemented with pure CSS.

这实际上可以使用 CSS flexbox 模型轻松完成,通过设置flex-directionreverse,以便元素以与它们在 DOM 中的顺序相反的顺序显示。上面的截图来自这样一个小部件,用纯 CSS 实现。

Flexbox is very well supportedby 95% of modern browsers.

95% 的现代浏览器都很好地支持 Flexbox

.rating {
  display: flex;
  flex-direction: row-reverse;
  width: 9rem;
}
.rating div {
  flex: 1;
  align-self: flex-end;
  background-color: black;
  border: 0.1rem solid white;
}
.rating div:hover {
  background-color: lightblue;
}
.rating div[data-rating="1"] {
  height: 5rem;
}
.rating div[data-rating="2"] {
  height: 4rem;
}
.rating div[data-rating="3"] {
  height: 3rem;
}
.rating div[data-rating="4"] {
  height: 2rem;
}
.rating div[data-rating="5"] {
  height: 1rem;
}
.rating div:hover ~ div {
  background-color: lightblue;
}
<div class="rating">
  <div data-rating="1"></div>
  <div data-rating="2"></div>
  <div data-rating="3"></div>
  <div data-rating="4"></div>
  <div data-rating="5"></div>
</div>

回答by rick

Big thanks to Mike and Robertc for their helpful posts!

非常感谢 Mike 和 Robertc 的有用帖子!

If you have two elements in your HTML and you want to :hoverover one and target a style change in the other the two elements must be directly related--parents, children or siblings. This means that the two elements either must be one inside the other or must both be contained within the same larger element.

如果您的 HTML 中有两个元素,并且您想要:hover更改一个元素并在另一个元素中更改样式,则这两个元素必须直接相关——父元素、子元素或兄弟元素。这意味着这两个元素要么必须一个在另一个内部,要么必须都包含在同一个更大的元素中。

I wanted to display definitions in a box on the right side of the browser as my users read through my site and :hoverover highlighted terms; therefore, I did not want the 'definition' element to be displayed inside the 'text' element.

当我的用户浏览我的网站和:hover突出显示的术语时,我想在浏览器右侧的框中显示定义;因此,我不希望“定义”元素显示在“文本”元素内。

I almost gave up and just added javascript to my page, but this is the future dang it! We should not have to put up with back sass from CSS and HTML telling us where we have to place our elements to achieve the effects we want! In the end we compromised.

我几乎放弃了,只是在我的页面中添加了 javascript,但这就是未来!我们不应该忍受来自 CSS 和 HTML 的后顾之忧,告诉我们必须将元素放置在哪里才能实现我们想要的效果!最后我们妥协了。

While the actual HTML elements in the file must be either nested or contained in a single element to be valid :hovertargets to each other, the css positionattribute can be used to display any element where ever you want. I used position:fixed to place the target of my :hoveraction where I wanted it on the user's screen regardless to its location in the HTML document.

虽然文件中的实际 HTML 元素必须嵌套或包含在单个元素中才能成为彼此的有效:hover目标,但 cssposition属性可用于在您想要的任何位置显示任何元素。我使用 position:fixed 将我的:hover操作目标放置在用户屏幕上我想要的位置,而不管它在 HTML 文档中的位置。

The html:

html:

<div id="explainBox" class="explainBox"> /*Common parent*/

  <a class="defP" id="light" href="http://en.wikipedia.or/wiki/Light">Light                            /*highlighted term in text*/
  </a> is as ubiquitous as it is mysterious. /*plain text*/

  <div id="definitions"> /*Container for :hover-displayed definitions*/
    <p class="def" id="light"> /*example definition entry*/ Light:
      <br/>Short Answer: The type of energy you see
    </p>
  </div>

</div>

The css:

css:

/*read: "when user hovers over #light somewhere inside #explainBox
    set display to inline-block for #light directly inside of #definitions.*/

#explainBox #light:hover~#definitions>#light {
  display: inline-block;
}

.def {
  display: none;
}

#definitions {
  background-color: black;
  position: fixed;
  /*position attribute*/
  top: 5em;
  /*position attribute*/
  right: 2em;
  /*position attribute*/
  width: 20em;
  height: 30em;
  border: 1px solid orange;
  border-radius: 12px;
  padding: 10px;
}

In this example the target of a :hovercommand from an element within #explainBoxmust either be #explainBoxor also within #explainBox. The position attributes assigned to #definitions force it to appear in the desired location (outside #explainBox) even though it is technically located in an unwanted position within the HTML document.

在此示例中,:hover来自其中的元素的命令的目标#explainBox必须是#explainBox或也在 之内#explainBox。分配给 #definitions 的位置属性强制它出现在所需的位置(外部#explainBox),即使它在技术上位于 HTML 文档中不需要的位置。

I understand it is considered bad form to use the same #idfor more than one HTML element; however, in this case the instances of #lightcan be described independently due to their respective positions in uniquely #id'd elements. Is there any reason not to repeat the id#lightin this case?

我知道#id对多个 HTML 元素使用相同的形式被认为是不好的形式;然而,在这种情况下,#light由于它们各自在唯一#idd 元素中的位置,可以独立描述。id#light在这种情况下,有什么理由不重复?

回答by CyberHawk

Only this worked for me:

只有这对我有用:

#container:hover .cube { background-color: yellow; }

Where .cubeis CssClass of the #cube.

.cube.css 的 CssClass在哪里#cube

Tested in Firefox, Chromeand Edge.

FirefoxChromeEdge 中测试。

回答by Temani Afif

Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hoverstate of the main element.

这是另一个想法,它允许您在不考虑任何特定选择器的情况下仅使用:hover主元素的状态来影响其他元素。

For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:

为此,我将依赖于自定义属性(CSS 变量)的使用。正如我们在规范中所读到的:

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritanceand cascaderules...

自定义属性是普通属性,因此它们可以在任何元素上声明,使用正常的继承级联规则解决...

The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.

这个想法是在主元素中定义自定义属性并使用它们来设置子元素的样式,由于这些属性是继承的,我们只需要在悬停时在主元素中更改它们。

Here is an example:

下面是一个例子:

#container {
  width: 200px;
  height: 30px;
  border: 1px solid var(--c);
  --c:red;
}
#container:hover {
  --c:blue;
}
#container > div {
  width: 30px;
  height: 100%;
  background-color: var(--c);
}
<div id="container">
  <div>
  </div>
</div>

Why this can be better than using specific selector combined with hover?

为什么这比使用特定选择器结合悬停更好?

I can provide at least 2 reasons that make this method a good one to consider:

我可以提供至少 2 个原因使这种方法成为一个值得考虑的好方法:

  1. If we have many nested elements that share the same styles, this will avoid us complex selector to target all of them on hover. Using Custom properties, we simply change the value when hovering on the parent element.
  2. A custom property can be used to replace a value of any property and also a partial value of it. For example we can define a custom property for a color and we use it within a border, linear-gradient, background-color, box-shadowetc. This will avoid us reseting all these properties on hover.
  1. 如果我们有许多共享相同样式的嵌套元素,这将避免我们复杂的选择器在悬停时定位所有元素。使用自定义属性,我们只需在悬停在父元素上时更改值。
  2. 自定义属性可用于替换任何属性的值及其部分值。例如,我们可以定义颜色的自定义属性,我们使用它内的borderlinear-gradientbackground-colorbox-shadow等,这将避免我们悬停正在重置所有这些属性。

Here is a more complex example:

下面是一个更复杂的例子:

.container {
  --c:red;
  width:400px;
  display:flex;
  border:1px solid var(--c);
  justify-content:space-between;
  padding:5px;
  background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;
}
.box {
  width:30%;
  background:var(--c);
  box-shadow:0px 0px 5px var(--c);
  position:relative;
}
.box:before {
  content:"A";
  display:block;
  width:15px;
  margin:0 auto;
  height:100%;
  color:var(--c);
  background:#fff;
}

/*Hover*/
.container:hover {
  --c:blue;
}
<div class="container">
<div class="box"></div>
<div class="box"></div>
</div>

As we can see above, we only need one CSS declarationin order to change many properties of different elements.

正如我们在上面看到的,我们只需要一个 CSS 声明就可以改变不同元素的许多属性。