jQuery 判断鼠标从哪个方向进入元素

$(".item").bind("mouseenter mouseleave", function(e) {
	var w = $(this).width();
	var h = $(this).height();
	var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
	var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
	var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左”
	var eventType = e.type;
	var dirName = new Array('上方','右侧','下方','左侧');
	if(eventType == 'mouseenter'){
		console.log(dirName[direction]+'进入');
	}else{
		console.log(dirName[direction]+'离开');
	}
});

在列表中使用:

HTML:

文字
文字
文字
文字

JS(jQuery):

$(".item").bind("mouseenter mouseleave", function(e) {
	var w = $(this).width();
	var h = $(this).height();
	var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
	var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
	var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4; //direction的值为“0,1,2,3”分别对应着“上,右,下,左”
	var eventType = e.type;
	var styles = {
		center: {top: 0, left: 0},
		top: {top: '-100%', left: 0},
		right: {top: 0, left: '100%'},
		bottom: {top: '100%', left: 0},
		left: {top: 0, left: '-100%'}
	}
	var item = $(this).find('.mask').stop();
	if(eventType == 'mouseenter'){
		if(direction == 0) {
			item.css(styles.top);
		}else if(direction == 1) {
			item.css(styles.right);
		}else if(direction == 2) {
			item.css(styles.bottom);
		}else if(direction == 3) {
			item.css(styles.left);
		}
		item.animate(styles.center);
	}else{
		if(direction == 0) {
			item.animate(styles.top);
		}else if(direction == 1) {
			item.animate(styles.right);
		}else if(direction == 2) {
			item.animate(styles.bottom);
		}else if(direction == 3) {
			item.animate(styles.left);
		}
	}
});

CSS(Less): 

.item {
  float: left;
  position: relative;
  margin-right: 13px;
  margin-bottom: 13px;
  width: 290px;
  height: 160px;
  overflow: hidden;
  img {
    width: 290px;
    height: 160px;
  }
  .mask {
    position: absolute;
    top: 160px;
    left: 0;
    width: 290px;
    height: 160px;
    background: #C2001D;
    text-align: center;
    color: #fff;
    font-size: 18px;
    line-height: 160px;
  }
}

 

你可能感兴趣的:(前端开发,···,JavaScript,······,jQuery)