我在HTML页面中有SVG代码,我想使用jQuery更改SVG dom背景颜色,但我无法更改它,我该怎么做?
<desc>3014</desc>
<rect x="0" width="63" height="36.15" y="976.138" class="position-bounds st7"></rect>
<text x="7.17" y="1001.41" v:langid="1033" class="position-text st8">3014</text>
$(document).ready(function(){
$('text[text=3014]').attr('fill','red');
})
答案 0 :(得分:0)
你可以使用Snap.svg lib!它就像jQuery使用DOM一样简单。
<script src="http://snapsvg.io/assets/js/snap.svg-min.js"><script>
<script>
var s = Snap("css_selector");
s.attr({ fill,'red' });
<script>
答案 1 :(得分:0)
试试这个:
$(document).ready(function(){
$("text:contains(3014)").attr("fill","red");
})
示例:
<html>
<title>This is test</title>
<head>
</head>
<body>
<svg height="30" width="63">
<text x="0" y="15" fill="blue">3014</text>
</svg>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("text:contains(3014)").attr("fill","red");
})
</script>
</body>
</html>
答案 2 :(得分:0)
fill属性更改字体颜色但不更改背景。使用答案here和函数here中提供的方法,我创建了一个可能仅使用jQuery / Javascript为您工作的代码段。
如果您不需要使用jQuery / Javascript将<defs>
元素及其子元素添加到SVG,但只需要jQuery来激活突出显示,那么请参阅以下示例:https://jsfiddle.net/t0eL0bre/7/
$(document).ready(function() {
$('#clicker').on('click', function() {
var defs = makeSVG('defs', {
id: 'd'
});
var filter = makeSVG('filter', {
id: 'solid',
'x': '0',
'y': '0',
width: '1',
height: '1'
});
var flood = makeSVG('feFlood', {
'flood-color': 'red'
});
var composite = makeSVG('feComposite', {
'in': "SourceGraphic"
});
// this only gets the first SVG element on the page
// you can also add it to all svg elements if you have more than one
// by using a loop
$svg = $('svg')[0];
// used javascript's appendChild() function
// instead of jQuery.append()
// since jQuery inserts the elements into the innerHTML
// of the element and not as dom child elements
// so it would not work
$svg.appendChild(defs);
$svg.appendChild(filter);
$solid = $('#solid')[0];
$solid.appendChild(flood);
$solid.appendChild(composite);
// target text element by it's content
$('text:contains(3014)').attr('filter', 'url(#solid)');
});
});
// function written by @bobince in the answer of this post: https://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element
function makeSVG(tag, attrs) {
var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg width="25%" height="25%">
<!-- <defs> <filter x="0" y="0" width="1" height="1" id="solid"><feFlood flood-color="red"/><feComposite in="SourceGraphic"/></filter></defs> -->
<desc>3014</desc>
<rect x="0" width="63" height="36.15" y="976.138" class="position-bounds st7"></rect>
<text x="7.17" y="15" v:langid="1033" class="position-text st8 ">3014</text>
</svg>
<button id="clicker">Change Background</button>