DIV菜单层实现代码

  他便给我截了个图是,QQ商城的分类菜单,效果如下:

DIV菜单层实现代码

  我看了一下,咦!咱们这博客园也是这种呀!我自己之前也没做过这种效果,正好自己试试!(我不是做美工的,不过到js略懂罢了!)

  一、分析:

  1,右边大分类肯定是一个层下面用divMenuContent表示

  2,左边鼠标移上去的那个应该也是个层,下面用divMenuItem表示

  问题:怎么样表现过如图的样子呢?左边和右边看起来是一体的!于是想到divMenuItem的右边为none,而且z轴高于divMenuContent,让它正好压在divMenuContent的边框上!

  下面是两个层的样式:

  

复制代码 代码如下:

  #divMenuItem

  {

  position:absolute;

  z-index:99;

  width:147px;

  height:25px;

  border:3px solid #963;

  border-right:0px;

  background-color:#FC9;

  display:none;

  }

  #divMenuContent

  {

  display:none;

  position:absolute;

  z-index:98;

  width:200px;

  height:505px;

  border:3px solid #963;

  background-color:#FC9;

  }

  然后布局一个页面测试用:

  

复制代码 代码如下:

  <body>

  <br />

  <br />

  <br />

  <ul class="menu" id="menu">

  <li>aaaaaaaaaaaaa</li>

  <li>bbbbbbbbbbbbb</li>

  <li>cccccccdccccc</li>

  <li>ddddddddddddd</li>

  <li>eeeeeeeeeeeee</li>

  <li>fffffffffffff</li>

  <li>ggggggggggggg</li>

  <li>hhhhhhhhhhhhh</li>

  </ul>

  <div id="divMenuItem"></div>

  <div id="divMenuContent"></div>

  </body>

  简单设置一下menu的样式:

  

复制代码 代码如下:

  body

  {

  margin:0px;

  padding:0px;

  }

  .menu

  {

  list-style-type:none;

  float:left;

  border:1px solid green;

  width:150px;

  }

  .menu li

  {

  height:25px;

  background-color:#CCC;

  border:1px solid red;

  }

  主要实现:

  

复制代码 代码如下:

  $("#menu li").mouseenter(function()

  {

  var offset=$(this).offset();

  $("#divMenuItem")

  .offset({

  top:offset.top,left:offset.left

  })

  .html($(this).html())

  .show()

  $("#divMenuContent")

  .offset({

  top:offset.top,left:offset.left+$(this).width()-1

  })

  .show()

  })

  这里主要就是定位问题了!逻辑上是对的,可发现除一次移上去显示正常外,以后每移上的第一个都有点错位!这里也是一直没搞明白是怎么回事!后来在show()后又offset()了一下就好了,希望高人指明。

  修改后的全部JS如下:

  

复制代码 代码如下:

  $(function(){

  $("#divMenuItem,#divMenuContent").mouseout(function(e)

  {

  if($(e.toElement).parent().attr("id")!="menu" && $(e.toElement).attr("id")!="divMenuContent")

  {

  $("#divMenuItem").hide();

  $("#divMenuContent").hide();

  }

  })

  $("#menu li").mouseenter(function()

  {

  var offset=$(this).offset();

  $("#divMenuItem")

  .offset({

  top:offset.top,left:offset.left

  })

  .html($(this).html())

  .show()

  .offset({

  top:offset.top,left:offset.left

  });

  $("#divMenuContent")

  .offset({

  top:offset.top,left:offset.left+$(this).width()-1

  })

  .show()

  /* .offset({

  top:offset.top,left:offset.left+$(this).width()-1

  });*/

  .offset({

  top:$("#menu li").first().offset().top,left:offset.left+$(this).width()-1

  });

  })

  })

  

  里面有一块注释,offset()那块,它和下面的offset()是两个效果,现在的效果图:

DIV菜单层实现代码

  注释部分换一下效果图:

DIV菜单层实现代码

  效果已在:IE6,7,8,chrome中测试通过!

  代码打包下载/201011/yuanma/menu_jquery1.rar