<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>慕课网-拖拽实现</title>
<style type="text/css">
#draggable{ width: 100px;height: 100px; position: absolute;top: 100px;left: 100px;border: 1px solid #ccc;background: #eee;padding: 10px;cursor: default;}
</style>
</head>
<body>
<div id="draggable">拖我</div>
<script type="text/javascript">
var oDrag = document.getElementById('draggable');
var isDraging = false;
var startX = 0;
var startY = 0;
oDrag.addEventListener('mousedown',function(e){
//鼠标事件1 - 在标题栏按下(要计算鼠标相对拖拽元素的左上角的坐标 ,并且标记元素为可拖动)
var e=e||window.event;
startX = e.pageX-g("oDrag").offSetLeft;
startY = e.pageY-g("oDrag").offSetTop;
isDragging=true;
})
document.onmouseup = function(e){
//鼠标事件3 - 鼠标松开的时候(标记元素为不可拖动)
isDragging=false;
}
document.onmousemove = function(e) {
//鼠标事件2 - 鼠标移动时(要检测,元素是否标记为移动)
var e = e||window.event;
var mouseX = e.pageX;
var mouseY = e.pageY;
var moveX = 0;
var moveY = 0;
if(isDragging === true){
moveX = mouseX - startX;
moveY = mouseY - startY;
var pageWidth = document.documentElement.clientWidth;
var pageHeight = document.documentElement.clientHeight;
var dialogWidth = oDrag.offsetWidth;
var dialogHeight = oDrag.offsetHeight;
var maxX = pageWidth-dialogWidth;
var maxY = pageHeight - dialogHeight;
moveX = Math.min(maxX,Math.max(0,moveX));
moveY = Math.min(maxY,Math.max(0,moveY));
oDrag.style.left = moveX+'px';
oDrag.style.top = moveY+'px';
};
</script>
</body>
</html>
鼠标按下事件里面计算相对偏移位置错了,,你都没有定义g()函数,怎么使用。而且oDrag已经是一个元素对象了。
最后一个函数,没有闭合}并且,if语句是怎么写的能放分号吗?if(isDragging === true)这句话中的isDragging 这个没有。你再看看你写的代码吧,右侧也有源码可以参考