<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文哥讨厌IE</title>
</head>
<body>
<div id="over" onmousedown="down(this,event)" style="width:100pxheight:30pxbackground:redposition:absoluteleft:20pxtop:500px" onmousemove="move(this,event)" onmouseup="seup(this,event)">
</div>
<script type="text/javascript">
var posX,posY
var downX,downY
var mark=false
function down(obj,event)
{
obj.style.cursor="move"
posX=obj.style.left
posY=obj.style.top
downX=event.clientX
downY=event.clientY
mark=true
///alert(posX)
///alert(posY)
}
function move(obj,event)
{
var moveX=event.clientX
var moveY=event.clientY
if (mark) {
obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX) + "px"
obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px"
}
}
function seup(obj,event)
{
if (mark) {
var moveX=event.clientX
var moveY=event.clientY
obj.style.left=parseInt(moveX) + parseInt(posX) - parseInt(downX)+ "px"
obj.style.top=parseInt(moveY) + parseInt(posY) - parseInt(downY)+ "px"
downX=moveX
downY=moveY
}
obj.style.cursor="default"
mark = false
}
</script>
</body>
</html>
原理就是通过比较鼠标的XY坐标来判断。我不知道有没有其他的方式了,就拿知道的来说。下面是实现代码。<script>
var lastX = null,
lastY = null
window.onmousemove = function(event){
var curX = event.clientX,
curY = event.clientY,
direction = ''
// console.info(event)
// console.info(event.clientX)
// console.info(event.clientY)
// 初始化坐标
if(lastX == null || lastY == null){
lastX = curX
lastY = curY
return
}
if(curX >lastX){
direction += 'X右,'
}else if(curX <lastX){
direction += 'X左,'
}else{
direction += 'X居中,'
}
if(curY >lastY){
direction += 'Y上'
}else if(curY <lastY){
direction += 'Y下'
}else{
direction += 'Y居中'
}
lastX = curX
lastY = curY
console.info(direction)
document.body.innerText = direction
}
</script>