我用js在浏览器上创建右击菜单,如果菜单下有菜单,我就用递归创建,代码片段如下
我传递给这个函数的第三个参数(items)是一个对象,如下:
{item1:"创建层", item2: "创建可拖拽层",创建子层:{item1:"创建一个可拖拽的子层",item2:"创建在父层范围内拖拽的层"}}
接着我为每个菜单绑定事件,代码如下
/** * 添加菜单事件 */ function addEvents() { var prefix_left = 50, preifx_top = 50, childs; if (self.mnuItems) { for (var i = 0, len = self.mnuItems.length; i < len; i++) { window._event.on(self.mnuItems[i].item, "mouseover", function() { setUnSelected(); this.className = "menuitem_mo"; return false; }); window._event.on(self.mnuItems[i].item, "mouseout", function() { setUnSelected(); return false; }); //如果是有子菜单的菜单,点击时显示子菜单 if (self.mnuItems[i].isChild == true) { window._event.on(self.mnuItems[i].item, "click", function(e) { e = window.event || e; childs = getParentToChilds(this); for (var j = 0, count = childs.length; j < count; j++) { if (childs[j].item.style.display == "none") { childs[j].item.style.display = "block"; } else { childs[j].item.style.display = "none"; } } if (e.cancelBubble) e.cancelBubble = true; else e.stopPropagation(); return false; }); } else {//其他菜单点击时,创建一个浮动层 window._event.on(self.mnuItems[i].item, "click", function(e) { var container = self.container || document.body || document.documentElement, left = 0, top; if ((e.clientX - prefix_left) < 0) left = 0; else left = e.clientX - prefix_left; if ((e.clientY - preifx_top) < 0) top = 0; else top = e.clientY - preifx_top; var box = document.createElement("div"); box.id = "div" + i; box.className = "box"; container.appendChild(box); box.style.left = left; box.style.top = top; self.menu.style.visibility = "hidden"; return false; }); } } } }
代码主要是那个判断,如果第一个判断成立,表示这个菜单项下有子菜单,所以点击它的时候是显示它下面的子菜单,另外的菜单点击的时候就在界面上创建一个层。现在问题是,那个显示子菜单的click事件,每次点击,会连续触发两次,导致子菜单还是显示不出来。我的事件绑定代码如下:
var event = window._event || {}; event.listeners = event.listeners || []; event.on = function(elem, type, func) { type = type.replace(/^on/i, ""); var callback = function(e) { func.call(elem, e); } if (elem.attachEvent) { elem.attachEvent("on" + type, callback); } else { elem.addEventListener(type, callback, false); } event.listeners[event.listeners] = [elem, type, func]; }
菜单创建出来后的html代码片段如下
<div id="rootMenu" class="skin0"> <div class="menuitems">创建层</div> <div class="menuitems">创建可拖拽层</div> <div class="menuitems">创建子层</div> <!-- 这个是父级菜单 --> <div class="menuitems" style="display: none;">创建一个可拖拽的子层</div> <!-- 这个是子菜单 --> </div>
给你一个关键字,事件冒泡,有空再具体看你的代码。
div的button事件会触发两次!
HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
</title>
<script type="text/javascript">
function SayHello(e) {
alert("Hello World");
e = window.event || e;
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div onclick="SayHello(event)" style="width:300px; height:300px; background-color:Green">
<input type="button" value="click me" onclick="SayHello(event)" />
</div>
</form>
</body>
</html>
你在创建层时是不是都给有click事件??代码的思路不对,只是我看过后的第一感觉,不过还是抽空整理一下你的代码吧