jQuery背景滑動跟隨的導航選單

antzone發表於2017-04-18

分享一段程式碼例項,它實現了橫向導航選單效果。

並且導航選單的背景會跟隨滑鼠滑動。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
div, p, h1, h2, h3, h4, h5, h6, ul, a, {
  margin: 0;
  padding: 0;
}
.box {
  width: 100%;
  height: 50px;
  background: #555;
}
.nav:after {
  content: '';
  display: block;
  clear: both;
}
.nav {
  position: relative;
  width: 1100px;
  height: 50px;
  margin: 0 auto;
  overflow: hidden;
}
.nav > li {
  float: left;
  height: 50px;
  font-size: 20px;
  color: #fff;
  list-style: none;
  font-weight: bold;
  line-height: 50px;
  padding: 0 30px;
  position: relative;
  z-index: 10;
  display: inline-block;
  cursor: pointer;
  overflow: hidden;
}
.nav > .active {
  background: red;
  padding: 0 50px;
}
.leftbox {
  position: absolute;
  top: 0;
  left: 40px;
  background: #f00;
  width: 140px;
  height: 50px;
  z-index: 0;
}
</style>
<script src='http://libs.baidu.com/jquery/2.0.0/jquery.js'></script>
<script>
$(document).ready(function() {
  $('li').mouseover(function() {
    li_W = parseInt($(this).width()); //當前li的寬
    li_pad = $(this).css('padding'); //當前li的內邊距
    li_pad = (li_pad.split('px')[1]) * 2; //當前li的內邊距
    W = li_W + li_pad + 'px'; //要設定的移動背景的寬
 
    ul_left = $('.nav').offset().left;
    li_left = $(this).offset().left;
    var L = (li_left - ul_left);
    $('.leftbox').stop().animate({
      left: L + 'px'
    }, 100, function() {
      $('.leftbox').css('width', W); //設定移動背景的寬
    });
  });
  $('ul').mouseout(function(e) {
    var ul = $('ul')[0];
    var e = e || window.event;
    if (!isMouseLeaveOrEnter(e, ul)) {
      return false;
    }
    //console.log("=============");
    $('.leftbox').css('width', '100px').stop().animate({
      left: '40px'
    }, 500);
  });
 
  function isMouseLeaveOrEnter(e, handler) {
    var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
    while (reltg && reltg != handler) {
      reltg = reltg.parentNode;
    }
    return (reltg != handler);
  }
})
</script>
</head>
<body>
  <div class="box">
    <ul class="nav">
      <div class="leftbox"></div>
      <li class="active">新聞</li>
      <li>網頁</li>
      <li>資訊</li>
      <li>娛樂</li>
      <li>軍事</li>
      <li>網際網路</li>
      <li>網頁</li>
      <li>資訊</li>
      <li>娛樂</li>
      <li>軍事</li>
      <li>網際網路</li>
    </ul>
  </div>
</body>
</html>

相關文章