将css样式表应用于内联svg元素,而不在页面上加载它

时间:2013-06-21 10:53:41

标签: javascript jquery css regex svg

这里我要做的是通过查找其类并根据样式表中定义的属性将内联样式应用于元素,将内联css样式表应用于页面上的相对svg元素。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Creator: CorelDRAW X6 -->
<svg
xmlns="http://www.w3.org/2000/svg"
xml:space="preserve"
width="3.237in"
height="3.157in"
version="1.1"
style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
viewBox="0 0 3237 3157"
xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
        <style
        type="text/css">
            <![CDATA[
.str0 {stroke:#373435;stroke-width:4.16694;stroke-linejoin:round}
.fil3 {fill:none}
.fil0 {fill:#373435}
.fil1 {fill:#FEFEFE}
.fil2 {fill:#FEFEFE;fill-rule:nonzero}
]]>
       </style>
    </defs>
    <path
    id="_261044752"
    class="fil0"
    d="M267.784 510.417c106.059,-65.5195 214.002,-181.006 171.579,-314.403l-4.24253 -10.8414c-20.7402,-45.723 -69.7632,-62.6919 -116.429,-46.6655 -20.7402,8.95633 -34.8804,21.6839 -50.908,36.7667l-8.95515 8.48507 -8.48507 -8.48507c-16.0264,-15.0827 -30.1678,-27.8103 -51.3793,-36.7667 -46.1942,-16.0264 -95.216,0.942523 -115.956,46.6655l-4.24253 10.8414c-13.6701,42.8954 -11.7851,84.3759 0.942523,122.556 0,0.471261 0,0.471261 0,0.942523 1.41378,3.77127 2.82757,7.54254 4.24253,11.3138 29.2241,74.9471 98.0448,137.639 166.393,179.591l8.95633 5.6575 8.48388 -5.6575z"
    />
    </svg>


* 所以这里的代码类'fil0'应该在样式表及其属性中搜索,即'fill:#373435;'应该作为内联样式* 应用于'path' 已经试过一些正则表达但没有任何用处。

1 个答案:

答案 0 :(得分:1)

或许这样的事情?

<script>
  var stylesheet = document.styleSheets[0];
  var fil0 = stylesheet.cssRules[2].cssText;
  var path = document.getElementById("_261044752");
  path.removeAttribute("class");
  path.setAttribute("style", fil0.substring(fil0.indexOf("{") + 1,fil0.lastIndexOf("}")).trim());
</script>

如果你想用很多元素做这个,你可以调用document。getElementsByClassName(“fil0”)并遍历结果。