当我放入HTML代码时,js代码似乎正在工作,但是当我将其置于外部时无效,有人可以解释原因吗?在外部放置时,我将脚本标记放在</body>
之前,这是HTML代码,JS
代码是一个简单的可拖动div
HTML
<html>
<head>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<div id="container">
<div id="main-view">
<h1>Hello Welcome to the Site</h1>
<div id="dxy"> <!--Draggable -->
<p>Hello Drag me Around!</p>
</div>
</div>
</div>
<script type="text/javascript" src="js/drag.js"></script>
</body>
</html>
JS
window.onload = addListeners();
function addListeners(){
document.getElementById('dxy').addEventListener('mousedown',mouseDown,false);
window.addEventListener('mouseup',mouseUp,false);
}
function mouseUp(){
window.removeEventListener('mousemove',divMove,true);
}
function mouseDown(e){
window.addEventListener('mousemove',divMove,true);
}
function divMove(e){
var div = document.getElementById('dxy');
div.style.position = 'absolute';
div.style.top = e.clientY + 'px';
div.style.left = e.clientX = 'px';
}
答案 0 :(得分:3)
window.onload = addListeners();
需要
window.onload = addListeners;