仿京东左侧菜单 hover效果-简易demo
简单描述: 用到的知识点 css 中的绝对定位 以及 Js 中的事件冒泡(或事件委托)
1 .cont{display:inline-block;width:200px;height:200px;border:1px solid red;position:absolute;left:150px;top:2px;display:none;}
1 <div style="border:1px solid green;margin:30px auto;width:150px;" id="menu"> 2 3 <div class="item" id="div1" style="position:relative;"> 4 <span style="display:inline-block;background: #abcdef;width:150px;height:50px;cursor:pointer;">123</span> 5 <span id="span1" class="cont"> 6 hello1111111 7 hello1111111 8 hello1111111 9 hello1111111 10 hello1111111 11 </span> 12 </div> 13 14 <div id="div2" class="item" style="position:relative;"> 15 <span style="display:inline-block;background: red;width:150px;height:50px;cursor:pointer;">123</span> 16 <span class="cont">hello222222</span> 17 </div> 18 19 <div id="div3" class="item" style="position:relative;"> 20 <span style="display:inline-block;background: green;width:150px;height:50px;cursor:pointer;">123</span> 21 <span class="cont">hello333333</span> 22 </div> 23 24 </div>
1 window.onload = function(){ 2 var oSpan1 = document.getElementById("span1"); 3 var oMenu = document.getElementById("menu"); 4 var oSMenu = oMenu.childNodes; 5 6 for(var n=oSMenu.length-1; n>=0; n--){ 7 if(oSMenu[n].className == "item"){ 8 oSMenu[n].onmouseover = function(evt){ 9 var target = oTargetByClass._get_target_child(this.childNodes, "cont"); 10 target.style.display = "block"; 11 } 12 13 oSMenu[n].onmouseout = function(evt){ 14 var target = oTargetByClass._get_target_child(this.childNodes, "cont"); 15 target.style.display = "none"; 16 } 17 } 18 } 19 20 var oTargetByClass = { 21 22 _get_target_child: function(childNodes, child_class){ 23 for(var i = childNodes.length-1; i>=0; i--){ 24 if(childNodes[i].className == child_class){ 25 return childNodes[i]; 26 } 27 } 28 } 29 } 30 }