sequential-list.gif CSS的樣式設計中,順序列表(Sequential List)是一個很好用的語法,但有時候不得不手動的去修改原始碼嗎?在本篇文章中,教你如何使用 jQuery 去增加順序列表中的 CSS 樣式(classes),並產生圖型清單。第二個例子將告訴你如何在評論中,增加計數器。

在兩種情況中非常適用:
一、不能去手動修改原始檔的時候。(例如是使用痞客邦的部落格時候)
二、數量大的時候。(總不能一筆一筆去修改吧 )

 預覽效果

1a. 插入 jQuery 代碼

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">
$(document).ready(function(){

  $("#step li").each(function (i) {
    i = i+1;
    $(this).addClass("item" i);
   });

});
</script>

jQuery 會將原始碼輸出如下:

code explain

1b. CSS Code

設定<li>樣式的背景圖(step1.png, step2.png, step3.png, ......).

#step .item1 {
  background: url(step1.png) no-repeat;
}
#step .item2 {
  background: url(step2.png) no-repeat;
}
#step .item3 {
  background: url(step3.png) no-repeat;
}

step list

2a. Add Sequential Content

你也可以使用以下的技術,jQuery 的 prepend 語法,在每個<li>的序列中增加一些內容。下面的例子顯示了你如何在每個回應或留言中,增加序號。

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){

  $("#commentlist li").each(function (i) {
    i = i+1;
    $(this).prepend('<span class="commentnumber"> #' i '</span>');
   });

});
</script>

以上的語法,會加入 <span class="commentnumber"> 的標籤(tag) (還有 # + 1) 在每個 <li> 的 tag 內.

code explain

2b. 定義CSS

定義 <li> 元素的樣式為 position:relative 還有定義 .commentnumber 的樣式為  position:absolute 並把位置設定為靠右、置上的角落。

#commentlist li {
  position: relative;
}

#commentlist .commentnumber {
  position: absolute;
  right: 0;
  top: 8px;
}

commentlist counter


arrow
arrow
    全站熱搜

    jaichang2008 發表在 痞客邦 留言(0) 人氣()