代碼示範:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>無標題文檔</title> <style> </style> </head> <body> <p>單擊右鍵看效果~</p> <ul id="menu"> <li>撤銷</li> <li>重做</li> <li>複製</li> <li>粘貼</li> <li>大小寫轉換</li> <li>斷行符號</li> <li>拼字檢查</li> <li>建立</li> <li>自訂</li> <li>圖形選項</li> <li class="no">關閉</li> </ul> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
結構:
複製代碼 代碼如下:
<div id="wrap">
<ul id="menu">
<li><a href="">撤銷</a></li>
<li><a href="">重做</a></li>
<li><a href="">複製</a></li>
<li><a href="">粘貼</a></li>
<li><a href="">大小寫轉換</a></li>
<li><a href="">斷行符號</a></li>
<li><a href="">拼字檢查</a></li>
<li><a href="">建立</a></li>
<li><a href="">自訂</a></li>
<li><a href="">圖形選項</a></li>
<li class="no"><a href="">關閉</a></li>
</ul>
</div>
code是這樣:
複製代碼 代碼如下:
function $(id) {
return document.getElementById(id);
};
var EventUnit = {
addHandler: function(element, type, handler) {//添加事件處理常式
if(element.addEventListener) {
element.addEventListener(type, handler, false);
} else if(element.attachEvent) {
element.attachEvent('on' + type, handler);
} else {
element['on' + type] = handler;
};
},
getEvent: function(event) {
return event ? event : window.event;
},
preventDefault: function(event) {//取消事件預設動作
if(event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
};
}
}
EventUnit.addHandler(window, 'load', function() {
var wrap = $('wrap');
var menu = $('menu');
var menuStyle = menu.style.display;
var x = wrap.offsetLeft + wrap.clientWidth, y = wrap.offsetTop + wrap.clientHeight;
var w = 0, h = 0;
var left = 0, top = 0;
EventUnit.addHandler(wrap, 'contextmenu', function(event) {
event = EventUnit.getEvent(event);
EventUnit.preventDefault(event);
menu.style.display = 'block';
w = menu.clientWidth;
h = menu.clientHeight;
left = (x - event.clientX >= w) ? event.clientX - wrap.offsetLeft : event.clientX - wrap.offsetLeft - w;
top = (event.clientY + h <= y) ? event.clientY - wrap.offsetTop : event.clientY - wrap.offsetTop - h;
menu.style.left = left + 'px';
menu.style.top = top + 'px';
});
EventUnit.addHandler(document, 'click', function() {
menu.style.display = menuStyle;
});
});