我有一堆由 illustrator 生成的徽标,我想直接将其嵌入到我的网站中。svgs 都有一个<style>元素,其中在 svg 元素中定义了样式,如下所示:
<svg>
<style>
.st1 { fill:#ff00ff; }
.st2 { fill:#ff3421; }
/* ... and so on */
</style>
<!-- svg paths and shapes -->
</svg>
Run Code Online (Sandbox Code Playgroud)
问题是这些样式会相互干扰。因此,如果最后的图像定义了.st21 {fill:#555555}此样式,则此样式将应用于所有带有 的路径class="st21",包括来自所有先前加载的 svg 图像的路径。
在另一个线程中,有人建议用<object>标签包装我的 svg-xml ,这似乎不起作用。
在不接触实际 SVG 代码的情况下,如何确保内联 SVG 样式不会相互干扰?
这里有一支笔来说明这个问题:https : //codepen.io/pwkip/pen/RLPgpW
我想出了一个 JavaScript 解决方案。尽管如果您使用大量 SVG,这可能有点过大且缓慢。但到目前为止效果很好。
我所做的是,迭代所有 SVG 并收集/解析它们的 CSS 样式。我收集所有类名称和属性,并将它们手动应用到 SVG 元素上。
const svgCollection = document.querySelectorAll( 'svg' );
function parseStyles( styleTag ) {
if ( !styleTag ) {
return {};
}
const classCollection = {};
const plain = styleTag.innerHTML;
const regex = /\.([^\s{]+)[\s]*\{([\s\S]+?)\}/;
const propertyRegex = /([\w\-]+)[\s]*:[\s]*([^;]+)/;
const result = plain.match( new RegExp( regex, 'g' ) );
if ( result ) {
result.forEach( c => {
const classResult = c.match( regex );
const propertiesResult = classResult[ 2 ].match( new RegExp( propertyRegex, 'g' ) );
const properties = propertiesResult.reduce( ( collection, item ) => {
const p = item.match( propertyRegex );
collection[ p[ 1 ] ] = p[ 2 ];
return collection;
}, {} );
classCollection[ classResult[ 1 ] ] = properties;
} );
return classCollection;
}
return {};
}
function applyProperties( element, properties ) {
if ( !properties ) {
return;
}
Object.keys( properties ).forEach( key => {
element.style[ key ] = properties[ key ];
} );
}
function applyStyles( element, styles ) {
const classNames = ( element.getAttribute( 'class' ) || '' ).split( ' ' );
classNames.forEach( c => {
applyProperties( element, styles[ c ] );
} );
element.setAttribute( 'class', '' );
}
for ( let i = 0; i < svgCollection.length; i += 1 ) {
const svg = svgCollection[ i ];
const styles = parseStyles( svg.querySelector( 'style' ) );
const elements = svg.querySelectorAll( '[class]' );
for ( let j = 0; j < elements.length; j += 1 ) {
applyStyles( elements[ j ], styles );
}
}Run Code Online (Sandbox Code Playgroud)
<p>this shape should be blue:</p>
<svg height="210" width="210">
<style>
.st1 {
fill:blue;
}
</style>
<polygon points="100,10 40,198 190,78 10,78 160,198" class="st1"/>
</svg>
<p>this shape should be red:</p>
<svg height="210" width="210">
<style>
.st1 {
fill:red;
}
</style>
<ellipse cx="105" cy="80" rx="100" ry="50" class="st1" />
</svg>Run Code Online (Sandbox Code Playgroud)
尽管这很有效,但我不会建议它(正如您问题的评论中提到的)。CSS Properties最好在Presentation AttributesIllustrator 中设置