我已经通过对象块加载了一个SVG文档,并且我想以编程方式为每个组添加一个title标记,但我被卡住了。SVG的加载方式如下:
<object data="International_Telecommunication_Union_region.svg" type="image/svg+xml" id="worldMap">
</object>然后,我尝试获取其中一个组元素,如下所示(使用JQuery 1.11.2):
$('g .landxx .BR')但这将返回一个空列表。然而,如果我执行以下操作,我会在Chrome的控制台中显示元素:
console.log($('g .landxx .BR'))有没有人能推荐一个正确的方法来添加子元素到通过object标签加载的SVG中。我更愿意使用JQuery的便利性,但是如果这不是一种选择,我很有兴趣听到一些替代方案。
顺便说一句,我确实看过拉斐尔,但这似乎只允许操作通过拉斐尔创建的SVG对象,所以在这种情况下不是一个可行的选择。
发布于 2015-04-17 10:27:41
只需使用img标签修改类似问题的答案:
How to change color of SVG image using CSS (jQuery SVG image replacement)?
将src属性更改为data,并向您的class=标记添加一个对象“svg”。我对它进行了测试,我可以用css改变填充和笔触,用jquery应该也行得通。
jQuery('object#worldMap').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('data');
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');
});https://stackoverflow.com/questions/29594906
复制相似问题