jQuery中的attr()是否强制小写?

我正在尝试操纵svg’viewBox’属性,它看起来像这样:

 ...  

运用

 $("svg").attr("viewBox","..."); 

但是,这会在名为“viewbox”的元素中创建一个新属性。 注意小写而不是预期的camelCase。 我应该使用另一种function吗?

我能够使用纯javascript来获取元素并使用设置属性

 var svg = document.getElementsByTagName("svg")[0]; 

 svg.setAttribute("viewBox","..."); 

根据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'); 

如果您计划添加元素,则还需要在创建元素时指定命名空间以及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'); 

你可以使用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’)。

你想确保在操作之前删除attr(如果它已经存在)

 $("svg").removeAttr("viewBox") 

然后重新创建它

 $("svg").attr("viewBox","...");