如何解决是否有一个可以根据样式选择元素的可靠选择器?
这是我编写的函数。可以很好地获取具有特定属性的最接近元素:
// Example of attribute if id
export function getClosestAttribute(
element: SVGElement,attribute: keyof typeof svgAttributeToCssStyle,excludeElement: boolean
): string | null {
let firstIncludedEl: Element | null = element;
if (excludeElement) {
firstIncludedEl = element.parentElement;
}
if (!firstIncludedEl) {
return null;
}
const closestEl = firstIncludedEl.closest(`[${attribute}]`);
if (!closestEl) {
return null;
}
return closestEl.getAttribute(attribute);
}
是否可以为样式编写类似的内容?例如。我想选择任何具有style="...fill:..."
的元素吗?
解决方法
更新
另一种方法是匹配两个规则。第一个“起始于”规则匹配:color: red
,但不匹配background-color: red
。
div[style^="color:"] {
text-decoration: underline;
}
当字符串出现在style
值后面的任何位置时,第二条规则匹配:
div[style*=" color:"] {
text-decoration: underline;
}
然后我们将它们链接在一起:
div[style^="color:"],div[style*=" color:"] {
text-decoration: underline;
opacity: 0.5;
}
<div style="background-color: red;">Should not match
</div>
<div style="font-size: 20px; color: red;">Match
</div>
<div style="color: red; font-size: 32px;">Match
</div>
<div style="font-size: 20px; background-color: red;">Should not match
</div>
__
您可以使用attribute selector并查找包含所选字符串的style
值。但是,空白很重要。如果您正在寻找style*="color: red"
,但您的style
值在color:
和red
之间没有空格,那么选择器将找不到。
[attr * = value] 表示属性名称为attr的元素,其值在字符串中至少包含一个值。
示例:
div[style*="color: red"] {
text-decoration: underline;
}
<div style="color: blue;">Regular div
</div>
<div style="color: red;">Add an underline
</div>
,
尝试:
div[style^="color: red"] {
text-decoration: underline;
}
如果样式属性以颜色:红色开头,则此方法有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。