鼠标悬浮遮罩层动画方式滑动切换效果

快乐打工仔 分类:实例代码

分享一段代码实例,它实现了鼠标悬浮,元素出现遮罩的功能。

遮罩层能够自适应大小,并且切换具有滑动效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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()一章节。

鼠标悬浮遮罩层动画方式滑动切换效果,这样的场景在实际项目中还是用的比较多的,关于鼠标悬浮遮罩层动画方式滑动切换效果就介绍到这了。

鼠标悬浮遮罩层动画方式滑动切换效果属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容