window.onload = function(){ var ul = document.querySelector('ul'); var aLi = document.querySelectorAll('li'); var winW = window.innerWidth; var winH = window.innerHeight; for (var i = 0; i < aLi.length; i ++) { aLi[i].onmouseenter = function(){ if(!this.children[0]){ findUl(this.parentNode); return; }; this.children[0].style.display = 'block'; this.children[0].style.zIndex = '2'; this.children[0].style.left = '198px'; this.children[0].style.top = '0px'; var l = offsetFn(this.children[0]).left; var t = offsetFn(this.children[0]).top; if (winW - l < ul.offsetWidth) { this.children[0].style.left = '-200px'; } if (winH - t < this.children[0].offsetHeight) { this.children[0].style.top = -this.children[0].offsetHeight+50 + 'px'; } } } /* * findUl 找到孙子ul并隐藏孙子及孙子下所有的ul * obj 鼠标经过的li的父级ul * 利用递归 逐级找到ul以及ul下所有的ul,并隐藏所有找到的ul */ functionfindUl(obj){ var lis = obj.children; //获取元素儿子 for (var i=0; i < lis.length; i ++) { if(lis[i].children[0]){ findUl(lis[i].children[0]); //递归 lis[i].children[0].style.display = 'none';//找完后,隐藏元素儿子 } } } functionoffsetFn(obj) { var t = 0; var l = 0; while(obj){ var bT = parseInt(getStyle(obj,"borderTopWidth")); var bL = parseInt(getStyle(obj,"borderLeftWidth")); t += obj.offsetTop + bT ; l += obj.offsetLeft + bL; obj = obj.offsetParent; } return {"top":t,"left":l}; } functiongetStyle(obj,attr) { if (obj.currentStyle) { return obj.currentStyle[attr]; }else{ return getComputedStyle(obj,null)[attr]; } } //鼠标右键 document.oncontextmenu = function(e){ var e =e || window.event; findUl(ul); ul.style.display = 'block'; var x = e.clientX; var y = e.clientY; if (winW - x < ul.offsetWidth) { x -= ul.offsetWidth; } if (winH - y < ul.offsetHeight) { y -= ul.offsetHeight; } ul.style.left = x + 'px'; ul.style.top = y + 'px'; returnfalse; } }