【问题标题】:edit :not() selector with javascript使用 javascript 编辑 :not() 选择器
【发布时间】:2020-07-09 09:25:01
【问题描述】:

我在 CSS 中为 .square 类提供了这个选择器

.square:not(:hover){
}

我想通过 JavaScript 为其添加自定义属性。

我试过这样做,但没有成功。

document.querySelectorAll('.square:not(:hover)').forEach((item) => {
  item.style.transition = `background ${animation_delay}s`;
});

VanillaJS 有什么办法吗?

【问题讨论】:

标签: javascript html css dom css-selectors


【解决方案1】:

访问/修改<style>标签的方式如下:

// suggest you add an id to your style tag
var style = document.querySelector('style');

var var sheet = style.sheet; // <-- CSSStyleSheet

var rules = sheet.rules; // <-- CSSRuleList

// keep the number of rules small/ordered 
// in the sheet you want to mutate, so you can 
// find them easily
rules[0].selectorText
// > selectorText: ".wmd-snippet-button span"

rules[0].style.backgroundColor
// > ""

rules[0].style.backgroundColor = 'black'
// > "black" // <-- (and see the change in the page!)

在 MDN 上查看更多信息 CSSStyleSheetCSSRuleList 页面。

*注意:此方法将改变您在样式表中的规则,而不是您展示的循环遍历所有当前匹配的元素并对其应用内联样式的方法。

【讨论】:

    【解决方案2】:

    document.querySelectorAll('.square:not(:hover)') 应该返回一个节点列表。 语法没有错。

    使用chrome开发工具,首先验证DOM中是否存在.square:not(:hover)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 2011-03-13
      • 1970-01-01
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-25
      相关资源
      最近更新 更多