-
Notifications
You must be signed in to change notification settings - Fork 0
/
拖拽事件处理.html
58 lines (50 loc) · 1.36 KB
/
拖拽事件处理.html
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
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
html, body { padding:0; margin:0; }
</style>
</head>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = 960, height = 500, r = 50;
var data = [
[width / 2 - r, height / 2 - r],
[width / 2 - r, height / 2 + r],
[width / 2 + r, height / 2 - r],
[width / 2 + r, height / 2 + r]
];
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height)
.append('g');
var drag = d3.drag().on('drag', move);
svg.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr('transform', function(d) {
return 'translate(' + d[0] + ',' + d[1] + ')';
})
.attr('r', r)
.attr('fill', 'red')
.call(drag)
function move(d) {
var x = d3.event.x,
y = d3.event.y;
if(inBoundaries(x ,y)) {
d3.select(this)
.attr('transform', function(d) {
return 'translate(' + x + ',' + y + ')';
})
}
}
function inBoundaries(x ,y) {
return x >= (0 + r) && x <= (width - r) && y >= (0 + r) && y <= (height - r);
}
</script>
</body>
</html>