我正在尝试操纵svg'viewBox'属性,如下所示:
<svg viewBox="0 0 100 200" width="100" ...> ... </svg>
使用
$("svg").attr("viewBox","...");
但是,这会在名为“viewbox”的元素中创建一个新属性。请注意小写而不是预期的camelCase。我应该使用另一种功能吗?
答案 0 :(得分:21)
我能够使用纯JavaScript来获取元素并使用
设置属性var svg = document.getElementsByTagName("svg")[0];
和
svg.setAttribute("viewBox","...");
答案 1 :(得分:3)
每http://www.w3.org/TR/xhtml1/#h-4.2个“XHTML文档必须对所有HTML元素和属性名称使用小写。”
因此,为了避免在XHTML文档中将属性转换为小写,您需要使用document.createElementNS()
创建指定命名空间的元素,如:
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('viewBox', '0 0 512 512’);
如果您计划添加<use/>
元素,则还需要在创建元素时指定命名空间以及xlink:href
属性,例如:
var use = document.createElementNS('http://www.w3.org/2000/svg','use');
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#your_svg_id');
答案 2 :(得分:1)
你可以使用jQuery钩子:
['preserveAspectRatio', 'viewBox'].forEach(function(k) {
$.attrHooks[k.toLowerCase()] = {
set: function(el, value) {
el.setAttribute(k, value);
return true;
},
get: function(el) {
return el.getAttribute(k);
},
};
});
现在jQuery将使用你的setter / getters来操作这些属性。
注意 el.attr('viewBox', null)
会失败;你的钩子设定器不会被调用。相反,你应该使用el.removeAttr('viewBox')。
答案 3 :(得分:-2)
你想确保在操作之前删除attr(如果它已经存在)
$("svg").removeAttr("viewBox")
然后重新创建
$("svg").attr("viewBox","...");