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

Does the attr() in jQuery force lowercase?

本文关键字:是否 中的 attr jQuery      更新时间:2023-09-26

我正在尝试操作svg的"viewBox"属性,它看起来像这样:

<svg viewBox="0 0 100 200" width="100" ...> ... </svg>

使用

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

但是,这会在名为"viewbox"的元素中创建一个新属性。请注意小写字母,而不是预期的camelCase。还有其他我应该使用的功能吗?

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

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

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

Perhttp://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');

您可以使用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/getter来操作这些属性。

注意el.attr('viewBox', null)会失败;你的勾手不会被召唤。相反,您应该使用el.removeAttr('viewBox').

在操作之前,您需要确保删除已经存在的属性

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

然后重新创建

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