当前位置: 代码迷 >> JavaScript >> 使用javascript(jquery)从外部SVG文件获取或设置CSS类值
  详细解决方案

使用javascript(jquery)从外部SVG文件获取或设置CSS类值

热度:17   发布时间:2023-06-06 09:42:00.0

我有一个SVG文件,其中包含一些这种格式的CSS类

  <style type="text/css" id="style1">
    <![CDATA[
      .fill1 {fill:#D2D3D5}
      .fill2 {fill:#A9ABAE}
      .fill3 {fill:#96989A}
    ]]>
  </style>

svg文件通过使用以下标记显示在HTML文件中。

<object id="testObject" type="image/svg+xml" data="img/test.svg"></object>

有什么办法让我使用javascript或jquery获取fill1,fill2和fill3的填充值。 还可以更改这些填充颜色吗?

使用通用Javascript,您可以获取对象并操作任何单独的 :

// obtain document of object
var objectDoc = document.getElementById('testObject').contentDocument;
// obtain stylesheet
var stylesheet = objectDoc.getElementById('style1').sheet;

// find a certain rule
var rule2 = Array.from(stylesheet.cssRules).find(function (rule) {
    // make sure you reference a style rule and identify by selector string
    return rule.type === CSSRule.STYLE_RULE && rule.selectorText === '.fill2';
});

// get fill value
rule2.style.getPropertyValue('fill');
// set a different fill
rule2.style.setProperty('fill', '#676869');
  相关解决方案