模拟windows平台的上下文菜单

技术上没什么难的,就是定义一个隐藏的box,当触发上下文事件时显示它,当单击body任意处时又隐藏它。样式效果比较粗糙,请见谅~~~

Demo在这里

结构:

View Code
1 <div id="wrap">
2 <ul id="menu">
3 <li><a href="">撤销</a></li>
4 <li><a href="">重做</a></li>
5 <li><a href="">复制</a></li>
6 <li><a href="">粘贴</a></li>
7 <li><a href="">大小写转换</a></li>
8 <li><a href="">回车</a></li>
9 <li><a href="">拼写检查</a></li>
10 <li><a href="">新建</a></li>
11 <li><a href="">自定义</a></li>
12 <li><a href="">图形选项</a></li>
13 <li class="no"><a href="">关闭</a></li>
14 </ul>
15  </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;
	});
});
posted @ 2011-03-10 23:01  chemdemo  阅读(333)  评论(0编辑  收藏  举报