.player
{
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 10'><line x1='1' y1='1' x2='9' y2='9' stroke='red'/><line x1='1' y1='9' x2='9' y2='1' stroke='red'/></svg>");
width: 100%;
height: 100%;
display: inline-block;
}
.one
{
fill: black;
}
.two
{
stroke: white;
}
具有 player
类的元素将有一个 svg 背景图像。如果元素同时具有 player
和 one
或 two
类,是否可以更改 svg 的样式(如果它是内联的)所以?如果没有,我将如何通过上课来进行简单的颜色更改?理想情况下,我不想在 html 中引入任何更多标记并阻止对这么小的 svg 文件进行 http 访问。
最佳答案
正如 Douglas 所写,您只能使用内联“src”设置 IMG 元素的样式。
我使用这种技术:
将普通图像与您的 SVG 路径一起使用:
<img src="my.svg" alt="">
使用 JavaScript (jQuery) 将“src”转换为内联样式:
$('img').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
使用 CSS 设置 SVG 的样式:
path {
fill: #f00;
}
完成。
关于css - 样式内嵌 css 的 svg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31710057/