javascript元素迴圈插入效果程式碼例項

admin發表於2017-04-09

這樣的效果不知道實際應用中是否多見,不過可以通過程式碼例項學習一下相關的操作。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" gb2312">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.in{
  height:20px;
  line-height:20px;
  width:20px;
  background-color:blue;
  text-align:center;
  color:white;
}
</style>
<script type=text/javascript>
window.onload = function () {
  var oList = document.getElementById('list');
  var oAdd = document.createElement('li');
  oAdd.className = "in";
  oAdd.style.cssText = 'background-color:red;border-radius:50%';
  oList.insertBefore(oAdd, null);
  var num = -1;
  var max = oList.children.length;
  function incrementNumber() {
    num++;
    oList.insertBefore(oAdd, oList.getElementsByTagName('li')[num]);
    if (num == max) {
      num = -1;
    }
    if (num == 0) {
      num = 1;
    }
    setTimeout(incrementNumber, 1000);
  }
  setTimeout(incrementNumber, 1000);
}
</script>
</head>
<body>
<ul class="list" id="list">
 <li class="in">1</li>
 <li class="in">2</li>
 <li class="in">3</li>
 <li class="in">4</li>
 <li class="in">5</li>
 <li class="in">6</li>  
</ul>
</body>
</html>

上面的程式碼中,紅色的小球可以迴圈插入元素之間的空白位置,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).window.onload = function () {},文件內容完全載入完畢再去執行函式中的程式碼。

(2).var oList = document.getElementById('list'),獲取id屬性值為list的元素物件。

(3).var oAdd = document.createElement('li'),動態建立一個li元素物件。

(4).oAdd.className = "in",設定li元素的class屬性值為in。

(5).oAdd.style.cssText = 'background-color:red;border-radius:50%',再為元素設定指定的樣式,背景色為紅色,圓角。

(6).oList.insertBefore(oAdd, null),首先插入列表的末尾。

(7).var num = -1,宣告一個變數並賦值為-1。

(8).var max = oList.children.length,獲取olist元素下子元素的集合。

(9).function incrementNumber() {},此函式實現迴圈插入效果。

(10).num++,加1操作。

(11).oList.insertBefore(oAdd, oList.getElementsByTagName('li')[num]),在指定索引的li元素前面插入oAdd元素。

(12).if (num == max) {

  num = -1;

}

if (num == 0) {

  num = 1;

},如果num的值等於max,那麼就將num值重置為-1。

如果num值等於0,那麼num值設定為1。

(13).setTimeout(incrementNumber, 1000),使用地櫃的方式不斷呼叫函式本身。

二.相關閱讀:

(1).document.createElement()可以參閱document.createElement()一章節。

(2).className可以參閱js className一章節。

(3).cssText可以參閱javascript cssText一章節。

(4).insertBefore()可以參閱javascript insertBefore()一章節。

(5).children可以參閱javascript children一章節。

(6).getElementsByTagName()可以參閱document.getElementsByTagName()一章節。

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

相關文章