Noc*_*las 13 html javascript jquery svg
我正在尝试使用javascript修改svg标记以使其可调整大小,但我的更改没有任何效果.我需要这样做的原因是这个标签由我无法修改的库呈现,因此我似乎唯一的选择是使用javascript修改svg.
我知道这个脚本生成的标签是正确的,因为我能够将标签复制到一个新的html文档,它可以工作(我已将它包含在示例代码中),所以我似乎需要一些方法来强制svg认识到它已被更改(或修改svg的其他方式).
这是一个显示我的问题的HTML页面:
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var svg = $('#testsvg').find('svg')[0];
var w = svg.getAttribute('width').replace('px', '');
var h = svg.getAttribute('height').replace('px', '');
svg.removeAttribute('width');
svg.removeAttribute('height');
svg.setAttribute('viewbox', '0 0 ' + w + ' ' + h);
svg.setAttribute('preserveaspectratio', 'xminymin meet')
$(svg)
.css('width', '100%')
.css('height', '100%')
.css('background-color', 'white');
});
</script>
</head>
<body style="background-color: #333;">
<div style="width: 80%; height: 40%;">
<svg id="resultsvg" xmlns="http://www.w3.org/2000/svg" version="1.1" style="width: 100%; height: 100%; background-color: white; " viewbox="0 0 100 100" preserveaspectratio="xminymin meet">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" fill="red"></circle>
</svg>
</div>
<div id="testsvg" style="width: 80%; height: 40%;">
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100px" height="100px">
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" fill="red" />
</svg>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Rob*_*son 24
SVG区分大小写
svg.setAttribute('viewbox', '0 0 ' + w + ' ' + h);
svg.setAttribute('preserveaspectratio', 'xminymin meet')
Run Code Online (Sandbox Code Playgroud)
应该写
svg.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
svg.setAttribute('preserveAspectRatio', 'xMinYMin meet')
Run Code Online (Sandbox Code Playgroud)
<svg>元素的宽度和高度是属性而不是样式(不像html)所以你应该使用setAttribute('width', '100%')而不是.css('width', '100%')
jQuery将属性名称转换为小写; 例如,viewBox它将设置而不是设置属性viewbox.不幸的是,SVG(XML方言)元素属性名称区分大小写.
如果您想要一致地使用jQuery,您可以使用它$.attrHooks来处理区分大小写的属性:
['preserveAspectRatio', 'viewBox'].forEach(function(k) {
// jQuery converts the attribute name to lowercase before
// looking for the hook.
$.attrHooks[k.toLowerCase()] = {
set: function(el, value) {
if (value) {
el.setAttribute(k, value);
} else {
el.removeAttribute(k, value);
}
return true;
},
get: function(el) {
return el.getAttribute(k);
},
};
});
$(document).ready(function() {
var svg = $('#testsvg');
var w = svg.attr('width').replace('px', '');
var h = svg.attr('height').replace('px', '');
svg.attr({
width: '100%',
height: '100%',
viewBox: [0, 0, w, h].join(' '),
preserveAspectRatio: 'xMidYMid meet'
})
});
Run Code Online (Sandbox Code Playgroud)
注意el.attr('viewBox', null)会失败; 你的钩子设定器不会被调用.相反,你应该使用el.removeAttr('viewBox')或el.attr('viewBox', false).
对于像笔画这样的其他属性,我会将它们放在样式表中.
svg {
background-color: white;
}
circle {
fill: red;
stroke: black;
stroke-width: 1px;
}
Run Code Online (Sandbox Code Playgroud)
如果需要添加/ toggle类来更改特定元素的样式,则需要使用jQuery 1.12+或jquery 2.2+.