如何检测右上角左下方的屏幕区域JavaScript?我有4个箭头用于滑块,但我只想在鼠标悬停在特定区域时显示。
$('.container').mousemove(function (e) {
if (e.clientY < $('.container').height() / 2) {
console.log('top');
} else {
console.log('bottom');
}
if (e.client X < $('.container').width() / 2) {
console.log('left');
} else {
console.log('right');
}
});
答案 0 :(得分:5)
您会考虑CSS :hover
建议吗?它可能更简单。添加了字体真棒箭头作为示例。
html,
body {
height: 100%;
width: 100%;
}
.top {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 40px;
background: lightgray;
}
.left {
position: absolute;
top: 40px;
left: 0;
bottom: 40px;
width: 40px;
background: lightgray;
}
.right {
position: absolute;
top: 40px;
right: 0;
bottom: 40px;
width: 40px;
background: lightgray;
}
.bottom {
position: absolute;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 40px;
background: lightgray;
}
.top:hover,
.left:hover,
.right:hover,
.bottom:hover {
cursor: pointer;
background: gray;
}
.top:hover i,
.left:hover i,
.right:hover i,
.bottom:hover i {
display: block;
}
i.fa {
display: none;
text-align: center;
line-height: 40px;
font-size: 24px;
}
i.fa.fa-arrow-right,
i.fa.fa-arrow-left {
position: absolute;
top: 50%;
transform: translate(50%, -50%);
}
&#13;
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<div class="top"><i class="fa fa-arrow-up"></i></div>
<div class="left"><i class="fa fa-arrow-left"></i></div>
<div class="right"><i class="fa fa-arrow-right"></i></div>
<div class="bottom"><i class="fa fa-arrow-down"></i></div>
&#13;
答案 1 :(得分:0)
// define the rectangular areas
var areas = {
top: [0, 0, 500, 100], // [startX, startY, endX, endY]
left: [0, 0, 100, 500],
right: [100, 0, 500, 500],
bottom: [0, 400, 500, 500]
};
function getArea(x, y) {
for (var key in areas) {
var area = areas[key];
if (x <= area[0] && x >= area[2] && y <= area[1] && y >= area[3]) return key;
}
return null;
}
$('.container').mousemove(function (e) {
console.clear && console.clear();
console.log(getArea(e.clientX, e.clientY));
});