jQuery列表上下垂直滾動效果程式碼例項

admin發表於2017-04-15

本章節分享一段程式碼例項,它實現了列表垂直滾動效果。

並且滾動過程中具有間歇性,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<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>
          softwhy.com
          <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()一章節。

相關文章