菜单

模拟桌面的右键菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<ul>
<li>1</li>
<li>2</li>
<li>3
<ul>
<li>1</li>
<li>2</li>
<li>3
<ul>
<li>1</li>
<li>2</li>
<li>3
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</li>
<li>4</li>
</ul>
</li>
<li>4</li>
<li>5</li>
</ul>
</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
width: 200px;
position: absolute;
border-top: 1px solid aquamarine;
left: 198px;
top: 0;
display: none;
}
ul li{
height: 50px;
background-color: darkcyan;
font-size: 18px;
text-align: center;
line-height: 50px;
border: 1px solid aquamarine;
border-top: 0;
position: relative;
}
ul li:hover{
background-color: cadetblue;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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
*/

function findUl(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';//找完后,隐藏元素儿子
}
}
}

function offsetFn(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};
}
function getStyle(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';

return false;
}
}