JavaScript 元素跟隨滑鼠運動

admin發表於2017-04-17

分享一段程式碼例項,它實現了元素跟隨滑鼠運動的效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
#round {
  width: 40px;
  height: 40px;
  background-color: blueviolet;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -10px;
  margin-left: -10px;
}
</style>
<script type="text/javascript">
window.onload = function () {
  var roundObj = document.getElementById("round");
  document.onmousemove = function () {
    roundObj.style.left = event.clientX + "px";
    roundObj.style.top = event.clientY + "px";
  }
}
</script>
</head>
<body>
<div id="round"></div>
</body>
</html>

上面的程式碼實現了我們的要求,更多內容可以參閱相關閱讀。

相關閱讀:

(1).mousemove事件參閱JavaScript mousemove事件一章節。

(2).clientX參閱JavaScript event.clientX一章節。

相關文章