gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:05:04 26 4
gpt4 key购买 nike

给定一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com