鼠标和滚轮方向判断
1.鼠标进入方向判断:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="">
</head>
<body>
<div id="a" style="width:200px;height:200px;margin:100px auto;background:#06c">
</body>
<script>
document.getElementById("a").onmouseenter = function(e){
var _w = parseInt(this.style.width.replace("px", ""));
var _h = parseInt(this.style.height.replace("px", ""));
var _x = this.offsetLeft;
var _y = this.offsetTop;
var _m = "";
if(e.clientX < (_x + _w / 2))
{_m = "left";}
else if(e.clientX > (_x + _w / 2))
{_m = "right";}
else
_m = "center";
_m += "-";
if(e.clientY < (_y + _h / 2))
{_m += "top";}
else if(e.clientY > (_y + _h / 2))
{_m += "bottom";}
else
_m += "middle";
alert(_m);
}
</script>
</html>
2.滚轮滚动方向判断:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 300px; height: 300px; background: red;margin:100px auto;}
</style>
<script>
/*
鼠标滚轮事件
ie/chrome : onmousewheel
event.wheelDelta
上:120
下:-120
firefox : DOMMouseScroll 必须用addEventListener
event.detail
上:-3
下:3
return false阻止的是 obj.on事件名称=fn 所触发的默认行为
addEventListener绑定的事件需要通过event下面的preventDefault();
*/
window.onload = function() {
var oDiv = document.getElementById('div1');
oDiv.onmousewheel = fn;
if (oDiv.addEventListener) {
oDiv.addEventListener('DOMMouseScroll', fn, false);
}
//alert(2);
function fn(ev) {
var ev = ev || event;
var b = true; //判断向上或向下
if (ev.wheelDelta) {
b = ev.wheelDelta > 0 ? true : false;
} else {
b = ev.detail < 0 ? true : false;
}
//alert(b);
if ( b ) {
this.style.height = this.offsetHeight - 10 + 'px';
} else {
this.style.height = this.offsetHeight + 10 + 'px';
}
if (ev.preventDefault) {
ev.preventDefault();
}
return false;
}
if(document.attachEvent){
document.attachEvent('oncontextmenu', function() {
return false;
});
}
else{
document.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
//return false;
});}/**/
}
</script>
</head>
<body style="height: 2000px;">
<div id="div1"></div>
</body>
</html>