如何通过鼠标移动SVG元素?

时间:2017-10-30 08:19:48

标签: javascript html html5 svg

我想用鼠标移动这个多边形。我怎样才能做到这一点? 我想我应该使用一些像onMouseDown和onMouseMove得到新的位置和transform =“translate(x,y)但是我怎么能用JS做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用jquery UI中的draggable。这是您编辑的代码:



<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<script>
		$( function() {
			$( "#Layer_1" ).draggable();
		} );
	</script>
</head>

<body>
	<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 500 500" style="enable-background:new 0 0 500 500;" xml:space="preserve">
		<polygon class="st0" points=" 0,5 10,0 20,5 10,10" transform="translate(90,95) rotate(0 0 0)" stroke="none" fill="red"/>
	</svg>
</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

从下面参考,它正在运作:

<强> HTML:

<svg id="pointer" height="50" width="50">
    <polygon points="1,1 49,10 20,20 10,49"> 
    <!-- coordinates are in x,y format -->
   <!-- points go clockwise around the polygon -->
</svg>
<a href="bbc.co.uk" target="_blank">bbc</a>

<强> CSS:

#pointer {
  overflow: hidden;
  position: fixed;
  top: 200px;
  left: 200px;
  position: relative;
}
html {
  cursor: none;
}
a {
  font-size: 40px;
}
a:hover {
  cursor: pointer;
}

<强>使用Javascript:

var mouseX;
var mouseY;
window.onmousemove = handleMouseMove;
function handleMouseMove(event) {
  event = event || window.event;
  document.getElementById('pointer').style.top=event.clientY + "px";
  document.getElementById('pointer').style.left=event.clientX + "px";
}