You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检测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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:25:22