Len*_*Len 2 javascript svg dom
嗨,我有以下代码,我希望能够通过按一个按钮改变圆的半径我不知道在风格后使用什么.在document.getElementById("circle1")中.style.r ="10"; 部分代码
<html>
<head>
<script>
function circle() {
document.getElementById("circle").style.r="50";
}
function circle1() {
document.getElementById("circle1").style.r="10";
}
</script>
</head>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="svg" >
<circle id = "circle" cx = "100" cy = "800" r = "30" stroke="blue" stroke-width = "2" fill = "black"/>
<circle id = "circle1" cx = "20" cy = "500" r = "30" stroke="blue" stroke-width = "2" fill = "black"/>
</svg>
<body>
Set size of circles
<input type="button" onclick="circle()" value="big" />
<input type="button" onclick="circle1()" value="small" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如pp19dd所述,在他的回答中,关键是setAttribute(),但是因为看起来你想要增加/减少元素的r属性circle(而不是简单地将它设置为特定值),你也需要使用getAttribute()它.
这是一个相当简单的功能和实现,我认为,它可以做你想要的:
function circle(delta){
if (!delta){
return false;
}
else {
var e = document.querySelectorAll('circle[id^=circle]'),
changeBy = 10;
if (delta == 'big'){
e[0].setAttribute('r',parseInt(e[0].getAttribute('r'),10) + changeBy);
e[1].setAttribute('r',parseInt(e[1].getAttribute('r'),10) + changeBy);
}
else if (delta == 'small'){
e[0].setAttribute('r',parseInt(e[0].getAttribute('r'),10) - changeBy);
e[1].setAttribute('r',parseInt(e[1].getAttribute('r'),10) - changeBy);
}
}
}
var inputs = document.getElementsByTagName('input'),
buttons = [];
for (var i = 0, len = inputs.length; i < len; i++) {
if (inputs[i].type == 'button') {
inputs[i].onclick = function(){
circle(this.value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我没有对圆的r属性的无效负值进行任何检查.您可能想要自己添加.
我用它document.querySelectorAll()来简化(而不是两次显式调用document.getElementById()).这将导致Internet Explorer出现问题,但我不确定在Internet Explorer中实现SVG的程度如何,因此可能不会让事情变得更糟.
尽管如此,IE 9似乎完美地实现了演示.哪个让我惊讶不已...... IE 8,虽然更低,但我无法说.
参考文献:
| 归档时间: |
|
| 查看次数: |
5791 次 |
| 最近记录: |