滑鼠懸浮遮罩層動畫方式滑動切換效果

antzone發表於2017-04-19

分享一段程式碼例項,它實現了滑鼠懸浮,元素出現遮罩的功能。

遮罩層能夠自適應大小,並且切換具有滑動效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  margin: 0;
  padding: 0;
}
.box1 {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  float: left;
  position: relative;
}
.box2 {
  width: 200px;
  height: 200px;
  border: 1px solid #000;
  float: left;
  margin: 0 20px;
  position: relative;
}
.box3 {
  width: 400px;
  height: 300px;
  border: 1px solid #000;
  float: left;
  position: relative;
}
.mask {
  background: red;
  opacity: .5;
  position: absolute;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script>
$(function() {
  var aDiv = $('#box').children();
  aDiv.each(function() {
    $(this).mouseover(function() {
      var wi = $(this).width();
      var ht = $(this).height();
      var op = $(this).position();
      var txt = $(this).attr('txt-int');
      var mar = $(this).css('marginLeft');
      $('.mask').stop().animate({
        'width': wi,
        'height': ht,
        'left': op.left + parseInt(mar),
        'top': op.top,
        'lineHeight': ht + 'px'
      }, 300).find('a').html(txt).css({
        'width': wi,
        'height': ht,
        'display': 'block',
        'textAlign': 'center'
      })
    })
  })
})
</script>
</head>
<body>
  <div class='mask'><a href="#"></a></div>
  <div id="box">
    <div class="box1" txt-int="螞蟻部落一"></div>
    <div class="box2" txt-int="螞蟻部落二"></div>
    <div class="box3" txt-int="螞蟻部落三"></div>
  </div>
</body>
</html>

上面的程式碼實現了滑鼠懸浮出現遮罩層效果,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).$(function() {}),當文件結構完全載入完畢再去執行函式中的程式碼。

(2).var aDiv = $('#box').children(),獲取box元素下的說有div子元素。

(3). aDiv.each(function() {}),遍歷每一個div元素。

(4).$(this).mouseover(function() {}),為每一個div元素註冊mouseover事件處理函式。

(5).var wi = $(this).width(),獲取當前div元素的寬度。

(6).var ht = $(this).height(),獲取當前div元素的高度。

(7).var op = $(this).position(),返回當前div元素相對於文件的偏移量。

(8).var txt = $(this).attr('txt-int'),獲取當前div元素txt-int屬性值。

(9).var mar = $(this).css('marginLeft'),獲取元素的margin-left屬性值。

(10).$('.mask').stop().animate({

  'width': wi,

  'height': ht,

  'left': op.left + parseInt(mar),

  'top': op.top,

  'lineHeight': ht + 'px'

}, 300),以動畫方式設定遮罩層的尺寸和定位。

(11).find('a').html(txt).css({

  'width': wi,

  'height': ht,

  'display': 'block',

  'textAlign': 'center'

}),獲取連結a,然後將其文字內容設定為獲取的txt值。

並且將連結a設定為塊級元素,然後設定它的尺寸。

二.相關閱讀:

(1).children()方法可以參閱jQuery children()一章節。

(2).each()方法可以參閱jQuery each()一章節。

(3).mouseover事件可以參閱jQuery mouseover事件一章節。

(4).position()可以參閱jQuery position()一章節。

(5).stop()可以參閱jQuery stop()一章節。

(6).animate()可以參閱jQuery animate()一章節。

(7).parseInt()可以參閱javascript parseInt()一章節。

(8).find()可以參閱jQuery find()一章節。

相關文章