繁体   English   中英

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

[英]Get or set css class value from external SVG file using javascript(jquery)

我有一个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,您可以获取CSSStyleSheet对象并操作任何单独的CSSStyleDeclaration

// 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');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM