jQuery列表上下垂直滚动效果代码实例

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

本章节分享一段代码实例,它实现了列表垂直滚动效果。

并且滚动过程中具有间歇性,代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
li {
  list-style: none;
}
h3 {
  color: red;
  text-align: center;
  font: bold 18px/1.5 "microsoft yahei";
}
.prizes {
  height: 60px;
  width: 196px;
  position: relative;
  margin: 0 auto;
}
.prizes .leftbg {
  position: absolute;
  left: -15px;
  top: 10px;
  width: 15px;
  height: 40px;
  background: url(demo/jQuery/img/icon1.png) no-repeat;
}
.prizes .rightbg {
  position: absolute;
  right: -15px;
  top: 10px;
  width: 15px;
  height: 40px;
  background: url(demo/jQuery/img/icon2.png) no-repeat;
}
.prizes .prizesbox {
  height: 45px;
  width: 196px;
  overflow: hidden;
  margin-top: 5px;
}
.prizesbox ul {
  -webkit-padding-start: 0;
  margin-top: 0;
}
.prizes .prizesbox ul li {
  font: normal 14px/22px "microsoft yahei";
  color: #444444;
  text-align: center;
  margin-bottom: 20px;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(function () {
  setInterval(scrollPrize, 2000);
  function scrollPrize() {
    var $self = $('.prizesbox ul');
    $self.animate({
      'margin-top': "-60px"
    }, 600, function () {
      $self.css('margin-top', '0').find("li:lt(1)").appendTo($self);
    })
  }
})
</script>
</head>
<body>
  <h3>每2秒滚动一次</h3>
  <div class="prizes">
    <div class="leftbg"></div>
    <div class="rightbg"></div>
    <div class="prizesbox">
      <ul>
        <li>
          前端教程网
          <br>前端教程网欢迎您,只有努力才有未来
        </li>
        <li>
          div教程
          <br>没有人一开始就是高手,必须通过努力奋斗
        </li>
        <li>
          css教程
          <br>每一天都是新的要好好真心
        </li>
        <li>
          pipipi.net
          <br>下面秒都是虚幻,只有当前是真实的
        </li>
      </ul>
    </div>
  </div>
</body>
</html>

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

一.代码注释:

(1).$(function () {}),当文档结构完全加载完毕再去执行函数中的代码。

(2).setInterval(scrollPrize, 2000),每隔2秒调用一次scrollPrize函数,这就实现了每隔两秒实现一次上滚效果。

(3).function scrollPrize() {},此方法是实现滚动的核心。

(4).var $self = $('.prizesbox ul'),获取ul元素对象。

(5).$self.animate({

  'margin-top': "-60px"

}, 600, function () {

  $self.css('margin-top', '0').find("li:lt(1)").appendTo($self);

}),让ul元素以动画方式设置margin-top值为-60px,也就是向上滚动。

滚动完成之后,就将第一个li元素追加到ul的尾部,并且重置margin-top为0。

不断重复,就实现了垂直滚动效果。

二.相关阅读:

(1).setInterval()可以参阅setInterval()一章节。

(2).animate()可以参阅jQuery animate()一章节。

(3).css()可以参阅jQuery css()一章节。

(4).find()函数可以参阅jQuery find()一章节。 

(5).:lt可以参阅jQuery :lt一章节。

(6).appendTo()参阅jQuery appendTo()一章节。

jQuery列表上下垂直滚动效果代码实例,这样的场景在实际项目中还是用的比较多的,关于jQuery列表上下垂直滚动效果代码实例就介绍到这了。

jQuery列表上下垂直滚动效果代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容