首先將這三個功能以一個列表<ul>的形式放置。鼠標移入時樣式改變,移出時還原
<style>body{margin: 0;}ul{ margin: 0; padding: 0; list-style: none;}.list{ width: 100px; text-align: center; cursor: pointer; font:20px/40px '宋體'; background-color: #eee;}.in:hover{ background-color: lightblue; color: white; font-weight:bold;}</style><ul id="list" class="list"> <li class="in">頂部</li> <li class="in">點贊</li> <li class="in">評論</li></ul>菜單邏輯共包括阻止默認行為、顯隱效果和位置判斷三個部分
通常,點擊右鍵時,會彈出瀏覽器的默認右側菜單
通過return false可以實現阻止默認行為的效果,當然也可以使用preventDefault()和returnValue,詳細信息移步至此
document.oncontextmenu = function(){ return false;}右鍵菜單默認隱藏,點擊右鍵時顯示,點擊左鍵時再隱藏
關于元素顯隱,個人總結過共9種思路,本文就用最簡單的display屬性
<div id="test" style="height: 100px;width: 100px;background-color: pink;"></div><script>document.onclick = function(){ test.style.display = 'none';}document.oncontextmenu = function(){ test.style.display = 'block'; return false;}</script>鼠標對象共有6對坐標位置信息,若把右鍵菜單設置為fixed固定定位,則選擇clientX/Y即可
一般地,右鍵菜單的左上角位置應該是當前鼠標的坐標處
但是,還有另外2種情況需要考慮
【1】如果鼠標的位置到視口底部的位置小于菜單的高度,則鼠標的位置為菜單的底部位置
【2】如果鼠標的位置到視口右側的位置小于菜單的寬度,則視口的右側為菜單的右側
元素的尺寸信息共有偏移尺寸offset、可視區尺寸client和滾動尺寸scroll,此時菜單的寬高應該為偏移尺寸offsetWidth/offsetHeight(全尺寸包含width、padding、border)
<div id="test" style="position:fixed;height: 100px;width: 100px;background-color: pink;"></div><script>document.onclick = function(){ test.style.display = 'none';}document.oncontextmenu = function(e){ e = e || event; test.style.left = e.clientX + 'px'; test.style.top = e.clientY + 'px'; //注意,由于加法、減法的優先級高于大于、小于的優先級,所以不用加括號,詳細情況移步至此 if(document.documentElement.clientHeight - e.clientY < test.offsetHeight){ test.style.top = e.clientY - test.offsetHeight + 'px'; } if(document.documentElement.clientWidth - e.clientX < test.offsetWidth){ test.style.left = document.documentElement.clientWidth - test.offsetHeight + 'px'; } test.style.display = 'block'; return false;}</script>
新聞熱點
疑難解答
圖片精選