问题描述
我有一个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的填充值。 还可以更改这些填充颜色吗?
1楼
使用通用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');