javascript - 在 Javascript 中,是否可以向一个元素添加两次样式属性?

标签 javascript html css

给定一个 HTML 元素对象,是否可以在不求助于字符串操作的情况下向其添加两次相同的样式属性?

考虑以下示例:

<div style="width: 90%; width: calc(100% - 5em);"></div>
<h1 style="font-weight: bold; font-weight: 800;"></h1>
<p style="color: #cccccc; color: rgba(255, 255, 255, 0.8);"></p>

据我所知,通过 .style 设置样式属性(例如 element.style.color = "blue")或 .style.setProperty方法(例如 element.style.setProperty("color", "blue"))覆盖现有样式属性而不是附加它们。

拥有同一属性的多个定义允许我们利用 CSS 的级联特性,让我们在可用时使用更现代的 CSS 属性值,同时优雅地退回到“足够好”的值(最近添加的值)不支持。然而,我能看到做这样的事情的唯一方法是通过手动字符串操作。

最佳答案

除非您使用某些自定义 javascript 函数,否则您想要做的不可能

我猜这是因为 CSS specificity 的工作方式。

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. When specificity is equal to any of the multiple declarations, the last declaration found in the CSS is applied to the element. Specificity only applies when the same element is targeted by multiple declarations. Source: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

因此,当您在 style 属性中添加相同的 property 两次时,由于特殊性,将应用第二次。当您使用 .style.setProperty("propertyName", "propertyValue")element.style.propertyName = "propertyValue" 设置属性时,了解 Javascript 的“逻辑”行为>。是覆盖相同的属性,如果它已经存在,而不是添加一个新的。

关于javascript - 在 Javascript 中,是否可以向一个元素添加两次样式属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40127445/

相关文章:

Javascript 在两个相同字符之间获取子字符串?

javascript - 如何使表没有固定 <thead> 标题

jquery - 画一条线连接两个点击的 div 列

python - 使用 OAuth python

html - 在 CSS 中,如何使一个元素相对于包含元素居中,而不考虑其他同级元素?

javascript - 如何使用 jQuery 单独引用动态生成的 Bootstrap 面板

javascript - 将数据传递给 React 中的 "deeper down"组件

javascript - 在内存中查找实例

javascript - HTML5 : load a changing image from file on click

javascript - 响应式菜单 : undesirable link click on touch devices