JavaScript 的新领域 - 动态图片处理(SVG)-6
 
- UID
- 1066743
|

JavaScript 的新领域 - 动态图片处理(SVG)-6
事件
SVG 中的元素同样支持用户界面的事件。因此我们可以通过鼠标、键盘触发的各种事件改变 SVG 中的图形。这就使得在整个页面上可以进行丰富的图形的互动,而不需要借助于 Flash 插件。下面通过几个例子来说明对事件的运用,使用的都是 DOM3 事件规范中定义的方法。
模拟控件
HTML 中的单选钮、复选框、下拉列表等标准控件为用户输入和显示数据提供了各种友好的方式。过去我们只能“使用”它们,现在我们可以模拟甚至创造新的控件。我们先来模拟一个简单的单选钮的图形和行为。
图 2. 模拟单选钮 清单 5. 模拟的单选钮 1 之代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
| <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> 模拟单选钮 1</title>
<script language='JavaScript'>
/* <![CDATA[ */
function mimicRadio(){
var radName = 'pRadio', selectedId = 'pRadioSelected';
var ns = 'http://www.w3.org/2000/svg';//SVG 元素的命名空间。
var circles = document.getElementsByTagNameNS(ns, 'circle');
var selected = document.getElementById(selectedId);// 用于模拟选中状态的实心圆。
var circle;
for (var i = 0; i < circles.length; i++) {
circle = circles;
if (circle.getAttribute('name') === radName) {
// 上面提到过,在 XML 的 DOM 中,没有 getElementsByName 方法,所以我们需要手工检查元素的 name 属性。
// 为 circle 元素添加鼠标响应。
// 通过设置实心圆的位置和 style 中的 display 值,模拟单选钮被选中的行为。
circle.addEventListener('click', function(){
selected.setAttribute('cx', this.getAttribute('cx'));
selected.setAttribute('cy', this.getAttribute('cy'));
selected.style.display = 'block';
}, true)
}
}
}
window.addEventListener('load', mimicRadio, true);
/* ]]> */
</script>
</head>
<body>
<div id='svgDiv'>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 120 100"
style="border:1px solid; width:120px; height:100px; ">
<circle name='pRadio' cx="20" cy="50" r="6" stroke="black"
stroke-width='0.5' fill="white" />
<text x='28' y='53'>
上升
</text>
<circle name='pRadio' cx="70" cy="50" r="6" stroke="black"
stroke-width='0.5' fill="white"/>
<text x='78' y='53'>
下降
</text>
<circle id='pRadioSelected' cx="20" cy="50" r="2" style='display:none;'/>
</svg>
</div>
</body>
</html>
|
代码说明:
SVG
这里共有三个 circle 元素,其中两个作为空的选项的圆圈,第三用于标记选中的状态。circle 中控制大小和位置的几项属性我们之前都看过了。stroke-width 属性用于控制图形外框线条的宽度。name 属性是我们自定义的,用于将一组单选钮关联在一起。 |
|
|
|
|
|