如何检测DIV元素style属性中是否包含svg+xml字符串?
识别DIV元素style属性中的SVG字符串
我有一个包含背景图片的DIV元素,背景图有时是直接的图片路径,有时是生成的SVG。我需要识别DIV的style属性中是否包含svg+xml字符串。
我的两个DIV代码如下:
<div class="cover my-1" style="background-image: url('something.jpg');">Div 1 QQ</div> <div class="cover my-2" style="background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc...=');">Div 2</div>
我尝试了以下代码:
$(document).ready(function() { $(".cover.my-1:contains(QQ)").css("background-color", "yellow"); $(".cover.my-2:contains(svg+xml)").css("background-color", "yellow"); });
结果DIV 1因文本含QQ变色,但DIV 2未变色——因为svg+xml不在DIV文本内容中,而是在style属性里。请问如何识别DIV 2的style属性中的svg+xml?
解决方案
方法1:jQuery属性包含选择器
直接用jQuery的[attribute*=value]选择器,匹配style属性中包含指定字符串的元素:
$(document).ready(function() { $(".cover.my-1:contains(QQ)").css("background-color", "yellow"); // 匹配style属性包含svg+xml的.my-2元素 $(".cover.my-2[style*='svg+xml']").css("background-color", "yellow"); });
方法2:jQuery filter()自定义筛选
如果需要更灵活的判断逻辑(比如忽略大小写),可以用filter()方法:
$(document).ready(function() { $(".cover.my-1:contains(QQ)").css("background-color", "yellow"); $(".cover.my-2").filter(function() { // 检查当前元素的backgroundImage样式是否包含目标字符串 return this.style.backgroundImage.includes("svg+xml"); // 若需忽略大小写,可改为:return this.style.backgroundImage.toLowerCase().includes("svg+xml") }).css("background-color", "yellow"); });
方法3:原生JavaScript实现
不依赖jQuery的话,用原生JS同样可以实现:
document.addEventListener('DOMContentLoaded', function() { // 处理DIV1:匹配文本含QQ的元素 const div1 = document.querySelector(".cover.my-1"); if (div1 && div1.textContent.includes("QQ")) { div1.style.backgroundColor = "yellow"; } // 处理DIV2:检查style属性中的svg+xml const div2 = document.querySelector(".cover.my-2"); if (div2 && div2.style.backgroundImage.includes("svg+xml")) { div2.style.backgroundColor = "yellow"; } });
内容的提问来源于stack exchange,提问作者Claus
相关产品推荐
相关产品推荐

