问题描述
我正在使用直接放置在HTML文件中的SVG
I am working with an SVG that is directly placed into an HTML file
<svg>
Contents...
</svg>
使用javascript/jQuery,我想向SVG添加属性
Using javascript/jQuery I want to add an attribute to the SVG
$("svg").attr("viewBox", "0 0 166 361");
这是运行上述脚本后的修改后的SVG
Here is the modified SVG after running the above script
<svg viewbox="0 0 166 361">
Contents...
</svg>
请注意,它会放置viewbox而不是viewBox.由于viewbox(小写)不执行任何操作,因此我需要将其设置为viewBox(驼峰式)
notice it puts viewbox not viewBox. Since viewbox (lowercase) doesn't do anything I need it to be viewBox (camelcase)
有什么想法吗?
**更新**
我运行了一个小测试,从服务器端渲染了viewBox属性,然后运行了上面的脚本.您会看到1.从服务器端进行渲染就可以了. 2. jQuery无法识别camelCase viewBox属性,并以小写形式插入了另一个.
I ran a little test where I rendered the viewBox attribute from the server side, then I ran the script above. You can see that 1. When rendered from the server side, it is fine. 2. jQuery didn't recognize the camelCase viewBox attribute and inserted another one in all lower case.
<svg version="1.1" id="Layer_1" x="0pt" y="0pt" width="332"
height="722" viewBox=" 0 0 100 100" viewbox="0 0 166 332">
...
</svg>
推荐答案
我可能取决于您的编码文档类型. XHTML文档的所有HTML元素和属性名称都必须使用小写字母.我不确定HTML.
I might depend on your encoding document type. XHTML documents must use lower case for all HTML element and attribute names. I'm not sure about HTML.
更新2
我唯一能找到的解决方案是使用:
The only solution I could find is to use:
$("svg")[0].setAttribute("viewBox", "0 0 166 361");
更新
由于任何原因我都无法解释,我在自己的主机上进行了测试,因为JsFiddle始终使用XHTML(boo!).在所有情况下,它都是小写字母,但在FF,Chrome和IE9中它仍然是SVG元素(我不知道它们是否有效,因为我不知道SVG,我担心).
I can't explain it for any reason, I tested on my own host because JsFiddle always uses XHTML (boo!). In all cases it was lowercase, but it was still an SVG Element in FF, Chrome and IE9 (I don't know if they were valid because I don't know SVG I'm afraid).
这篇关于为什么jQuery自动降低大小写属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!