style change attribute javascript jquery svg attr lowercase

javascript - change - ¿El attr() en jQuery fuerza minúscula?



set element attribute javascript (4)

Podrías usar ganchos 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); }, }; });

Ahora jQuery usará tus setter / getters para manipular esos atributos.

Tenga en cuenta que el.attr(''viewBox'', null) habría fallado; Su gancho no se llamará. En su lugar, debe utilizar el.removeAttr (''viewBox'').

Estoy tratando de manipular el atributo svg ''viewBox'' que se parece a esto:

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

Utilizando

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

Sin embargo, esto crea un nuevo atributo en el elemento llamado "viewbox". Observe la minúscula en lugar de camelCase previsto. ¿Hay otra función que debería estar usando?


Pude usar javascript puro para obtener el elemento y establecer el atributo utilizando

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

y

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


Según http://www.w3.org/TR/xhtml1/#h-4.2 "Los documentos XHTML deben usar minúsculas para todos los nombres de atributos y elementos HTML."

Entonces, para evitar que el atributo se convierta a minúsculas en un documento XHTML, debe crear el elemento especificando un espacio de nombres usando document.createElementNS() , como:

var svg = document.createElementNS(''http://www.w3.org/2000/svg'', ''svg''); svg.setAttribute(''viewBox'', ''0 0 512 512’);

Si planea agregar un elemento <use/> también debe especificar el espacio de nombres al crear el elemento, así como el atributo xlink:href , como:

var use = document.createElementNS(''http://www.w3.org/2000/svg'',''use''); use.setAttributeNS(''http://www.w3.org/1999/xlink'', ''xlink:href'', ''#your_svg_id'');


desea asegurarse de eliminar el attr si ya existe antes de manipularlo

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

y luego recreando

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