2016-12-30 79 views
2

enter image description here如何檢測右上左下屏幕區域的JavaScript

如何檢測右上左下屏幕區域的JavaScript?我有四個箭頭滑塊,但我只想在鼠標懸停在特定區域時才顯示。

$('.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'); 
} 
}); 
+2

我只想讓覆蓋要檢查整個區域的元件,但要透明。然後當你檢測到鼠標懸停時,你可以顯示該元素。我知道這不會回答你的問題,但它是我將如何解決問題:) – Max

+0

http://api.jquery.com/offset/ – mplungjan

+0

謝謝最大我會嘗試。 – Bhautik

回答

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%); 
 
}
<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>

+0

感謝syden這將爲我多一個選擇。 – Bhautik

+1

@ bk129這是一個不錯的選擇。讓瀏覽器處理大小,如果需要更高級的行爲,則可以將懸停事件的偵聽器附加到任何給定的元素。使用:懸停和作用於懸停事件的工作量應少於評估鼠標座標所花費的工作量_任何時候都可以隨時移動。 –

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)); 
});