在下面的示例中,当我们悬停组1中的任何行时,组1的所有行都会更改 colored颜色 .我想将同样的逻辑应用于N个组.

假设我们有300个这样的组,每组3行.我们如何在不复制和粘贴300次css规则的情况下 for each 组实现此突出显示.

这能用纯css实现吗?

.parent:has(.group-1:hover) .group-1 {
  background-color: blue;
}
<body class="parent">
  <p class="group-1">Group 1</p>
  <p class="group-1">Group 1</p>
  <p class="group-1">Group 1</p>
  <p class="group-2">Group 2</p>
  <p class="group-2">Group 2</p>
  <p class="group-2">Group 2</p>
  <p class="group-3">Group 3</p>
  <p class="group-3">Group 3</p>
  <p class="group-3">Group 3</p>
</body>

推荐答案

如果您不能更改HTML以将它们包装在组中,您可以动态创建您的CSS,这样您就不需要手动写出所有规则.

// get all the elements with the group class
const allElements = document.querySelectorAll('p[class*="group-"]')

// get all the classNames from the elements
const allClassNames = Array.from(allElements).map(({
  className
}) => className);

// de-dupe
const groupings = new Set(allClassNames);

// build the selectors
const selectors = Array.from(groupings.values()).map(className => `.parent:has(.${className}:hover) .${className}`).join(",")

// your CSS you want to be in the rule
const theStyles = 'background-color: blue;'

// make a stylesheet
const styleEl = document.createElement("style");

// add it to the document
document.head.appendChild(styleEl);

//get the sheet
const styleSheet = styleEl.sheet;

//create the new rule
styleSheet.insertRule(`${selectors}{${theStyles}}`, 0);
P {
  margin: 0; padding: 0;
}
<div class="parent">
  <p class="group-1">Group 1</p>
  <p class="group-1">Group 1</p>
  <p class="group-1">Group 1</p>
  <p class="group-2">Group 2</p>
  <p class="group-2">Group 2</p>
  <p class="group-2">Group 2</p>
  <p class="group-3">Group 3</p>
  <p class="group-3">Group 3</p>
  <p class="group-3">Group 3</p>
</div>

Html相关问答推荐

创建具有圆锥渐变的水平CSS聚光灯

每次在视口中运行动画

如何在所有屏幕大小下使带有背景图像的伪元素作为标题的衬底?

在一行中对齐文本和图标

在每个列宽由带有固定值的minmax()函数定义的网格中,CSS如何为列分配空间?

如何将功能附加到嵌入式药剂中的按钮?

旧文本淡出,但新文本不会淡入,而是突然出现

如果最后一行的卡数少于其他行,则在使用flex grow使卡在调整大小时拉伸后,flex卡的宽度将被拉伸

为什么我不能覆盖 div 的样式?

调整 Rmarkdown 输出的 html_document 的标题和副标题之间的间距

当悬停时,同时影响相邻的两侧div

如何在 flex 项目中忽略子元素的宽度

不同屏幕尺寸的显示问题

是否可以使 huxtable 输出悬停?

在 html 邮箱的左侧和右侧制作多个元素很热门吗?

为什么图像会影响我的

为什么 `html` 上的 overflow: hidden 将滚动框移动到正文?

SVG 适用于 Safari,不适用于 Chrome

图标未定位到右上角

如何在 about:blank 网站上设置页面标题