DIV CSS 佈局教程網

用 jQuery + Bootstrap 做一個仿知乎的動態列表
編輯:JQuery入門技巧     

最近用 jQuery 搭配 Bootstrap 做了一個仿知乎動態列表的前端效果,基本功能都對齊了:全文展開收合、評論區展開、載入更多、帶動畫的點讚、回覆列表的 hover 顯示。

成品功能

1. 基本列表項

基本列表項

2. 列表項全文展開/收合(圖中為展開第一項)

全文展開狀態

3. 評論項展開

評論區展開

4. 列表資料載入(載入全部)

載入更多後的完整列表

5. 帶動畫效果的點讚功能

點讚動畫

6. 回覆列表的 hover 顯示功能

回覆按鈕的 hover 顯示

HTML 結構

設計上的關鍵是「用隱藏的樣板節點 + clone 產生列表項」,而不是在 JavaScript 裡拼 HTML 字串。這樣樣式一改,所有列表項跟著變,也不必擔心拼接出錯。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap-theme.min.css" />
<script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="scripts/jquery.json.min.js"></script>
<link rel="stylesheet" href="styles/main.css" />
<script src="scripts/test.js"></script>
</head>
<body>

<!-- 動態項樣板 -->
<div style="display:none;">
<div id="t_dn" class="dynamic_node">
  <meta class="dn_id" content=""/>
  <meta class="dn_user_id" content=""/>
  <div class="dn_left">
    <div class="dn_user_avatar"><a href=""><img class="img-thumbnail" src="" /></a></div>
    <div class="dn_zannum"><span></span></div>
    <div class="dn_dianzan">
      <a href=""><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></a>
    </div>
  </div>
  <div class="dn_right">
    <div class="dn_title">
      <span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span>
      <a href=""><span></span></a>
    </div>
    <div class="dn_right_top">
      <div class="dn_username">
        <a href=""><span class="dn_username_name"></span></a>
        <span class="dn_username_signature"></span>
      </div>
      <div class="dn_content_close1">
        <a href=""><span class="glyphicon glyphicon-triangle-bottom" aria-hidden="true"></span></a>
      </div>
    </div>
    <div class="dn_content">
      <a href="" class="dn_content_link"><span class="dn_content_digest"></span></a>
      <span class="dn_content_text"></span>
    </div>
    <div class="dn_action">
      <div class="dn_content_close2">
        <a href=""><span class="glyphicon glyphicon-triangle-top" aria-hidden="true"></span></a>
      </div>
      <a href=""><span class="dn_action_report">舉報</span></a>
      <a href=""><span class="dn_action_share">分享</span></a>
      <a href=""><span class="dn_action_comm">103條評論</span></a>
      <span class="dn_action_time"></span>
    </div>
    <div class="dn_comm">
      <div class="dn_comm_items"></div>
      <div class="dn_comm_showall">
        <button id="dn_comm_showall_button" type="button" class="btn btn-default btn-xs">顯示全部評論</button>
      </div>
      <div class="dn_comm_replay">
        <div class="dn_comm_replay_field">
          <textarea class="form-control" rows="2" placeholder="寫下你的評論..."></textarea>
        </div>
        <div class="dn_comm_replay_buttoms">
          <button type="button" class="btn btn-primary btn-sm">評論</button>
          <a href="" class="dn_comm_replay_buttoms_cancel">取消</a>
        </div>
      </div>
    </div>
  </div>
</div>
</div>

<!-- 評論項樣板 -->
<div id="t_dn_comm" class="dn_comm_item">
  <meta class="dn_comm_id" content="">
  <div class="dn_comm_item_left">
    <div><a href="#"><img class="img-rounded" src="images/user.png" /></a></div>
  </div>
  <div class="dn_comm_item_mid">
    <div class="dn_comm_item_middle_username">
      <a href="#"><span>用戶名</span></a>
    </div>
    <div class="dn_comm_item_mid_content"><span></span></div>
    <div class="dn_comm_foot">
      <div class="dn_comm_foot_left"><span>2015-09-08 12:00:09</span></div>
      <div class="dn_comm_item_mid_action">
        <a href="#"><span>回復</span></a>
        <a href="#"><span>舉報</span></a>
      </div>
    </div>
  </div>
  <div class="dn_comm_item_right">
    <div class="dn_comm_zannum"><span>5</span></div>
    <div class="dn_comm_dianzan">
      <a href="#"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></a>
    </div>
  </div>
</div>

<!-- 列表容器 -->
<div class="global">
  <div class="list_layout"></div>
  <div class="load_flag">
    <button id="load_flag_button" type="button" class="btn btn-default btn-s">加載更多</button>
    <div id="load_flag_info"><small>沒有更多了 !</small></div>
  </div>
</div>

</body>
</html>

CSS(main.css)

/* global navigation */
.nav {
  width:100%; height:3.5em; padding-top:0em; vertical-align:middle;
  background-image: -moz-linear-gradient(top, #99FFFF, #FFFFFF);
  background-image: -webkit-gradient(linear, left top, left bottom,
    color-stop(0, #99FFFF), color-stop(1, #FFFFFF));
  filter: progid:DXImageTransform.Microsoft.gradient(
    startColorstr='#99FFFF', endColorstr='#FFFFFF', GradientType='0');
}
.nav-content { width:1024px; margin-left:auto; margin-right:auto; }
.brand {
  font-size:2.5em; font-weight:lighter; color:#5e5e5e;
  font-family:"Microsoft JhengHei" !important;
}
.avatar img { padding:0.2em; }
#notice_num {
  visibility:visible; color:white; width:1.6em; height:1.6em;
  background:red; -moz-border-radius:1em; -webkit-border-radius:1em;
  border-radius:1em; position:fixed;
}
#nav_user_name, #nav_user_avatar { float:right; }
.content, .left, .right, .foot { width:1024px; margin-left:auto; margin-right:auto; }
.right { background-color:white; }
.foot span { font-size:0.8em; font-weight:lighter; }
.dashed-line { border-bottom:1px dashed; border-bottom-color:#C9C9C9; }

/* dynamic list */
.dynamic_node {
  width:100%; border-top:1px solid #eee;
  padding-bottom:1em; padding-top:1em; float:left;
}
.dn_left { width:50px; float:left; }
.dn_left img { width:50px; height:50px; }
.dn_dianzan, .dn_zannum {
  width:100%; float:left; margin-left:auto; margin-right:auto; text-align:center;
}
.dn_right { padding-left:1em; width:666px; float:left; }
.dn_title label { font-weight:lighter; color:#6b6b6b; }
.dn_title a span { color:#259; font-weight:bold; }
.dn_username_name { font-weight:bold; font-size:0.8em; color:#259; }
.dn_username_signature { font-size:0.8em; }
.dn_content_digest, .dn_content_text {
  float:left; font-size:0.8em; color:#363636; width:100%;
}
.dn_content_text { display:none; }
.dn_content_close1, .dn_content_close2 { float:right; display:none; font-size:1em; }
.dn_action { display:none; float:right; }
.dn_action span { float:right; margin-left:1em; margin-top:1em; font-size:0.8em; }
.dn_comm { float:left; width:100%; display:none; }
.dn_comm_items { float:left; width:100%; }
.dn_comm_item {
  float:left; margin-top:0.8em; border-top:1px solid #eee; padding-top:0.8em;
}
.dn_comm_item_left { width:50px; float:left; }
.dn_comm_item_mid  { width:560px; float:left; }
.dn_right_top { width:100%; float:left; }
.dn_comm_item_right { width:30px; float:right; text-align:center; }
.dn_comm_item_left img { width:30px; height:30px; }
.dn_comm_item_middle_username, .dn_comm_item_mid_content { float:left; font-size:0.8em; }
.dn_comm_item_mid_action { float:right; margin-left:1em; font-size:0.8em; display:none; }
.dn_comm_item_mid_action span { margin-left:1em; }
.dn_comm_dianzan, .dn_comm_zannum {
  font-size:1em; width:100%; margin-left:auto; margin-right:auto;
}
.dn_comm_zannum { color:#797979; }
.dn_comm_foot_left {
  float:left; padding-top:0.4em; color:#797979;
  width:50%; font-size:0.7em;
}
.dn_comm_replay {
  float:left; width:100%; margin-top:1em;
  padding-top:1em; border-top:1px solid #eee;
}
.dn_comm_replay_field { float:left; width:100%; margin-bottom:1em; }
.dn_comm_replay_buttoms a, .dn_comm_replay_buttoms button { float:right; }
.dn_comm_replay_buttoms_cancel { padding-top:0.5em; margin-right:1em; }
.dn_comm_showall {
  float:left; width:100%; margin-top:1em;
  padding-top:1em; border-top:1px solid #eee;
}
.dn_comm_showall #dn_comm_showall_button {
  float:left; width:80%; margin-left:10%; margin-right:10%; margin-top:1em;
  border-top:1px solid #eee;
}

/* layout */
.global { width:716px; }
.list_layout, .load_flag { width:100%; float:left; display:block; }
.load_flag { padding-top:1em; border-top:1px solid #eee; margin-bottom:3em; }
.load_flag button {
  float:left; width:80%; margin-left:10%; margin-right:10%;
}
.load_flag #load_flag_info {
  float:left; text-align:center; width:80%;
  margin-left:10%; margin-right:10%; display:none;
}

JavaScript(test.js)

$(document).ready(function () {
  url_user     = "https://user.com/i=";
  url_img      = "https://127.0.0.1/pages/";
  url_dianzan  = "https://dianzan.com";
  url_dn_detail = "https://dt.com/i=";

  layout_list = $(".list_layout");
  t_dn        = $("#t_dn");
  t_dn_comm   = $("#t_dn_comm");

  maxnum    = 2;  // 最大載入次數
  num       = 1;
  load_flag = $(".load_flag");

  function render_dn_list(arr_dn) {
    for (var i = 0; i < arr_dn.length; i++) {
      var node_dn = t_dn.clone();

      node_dn.find(".dn_id").attr("content", arr_dn[i]["ID"]);
      node_dn.find(".user_id").attr("content", arr_dn[i]["userid"]);
      node_dn.find(".dn_left .dn_user_avatar a").attr("href", url_user + arr_dn[i]["userid"]);
      node_dn.find(".dn_left .dn_user_avatar a img").attr("src", url_img + arr_dn[i]["avatar"]);
      node_dn.find(".dn_zannum span").text(arr_dn[i]["zan"]);
      node_dn.find(".dn_title a").attr("href", url_dn_detail + arr_dn[i]["fid"] + "#" + arr_dn[i]["ID"]);
      node_dn.find(".dn_title a span").text(arr_dn[i]["from"]);
      node_dn.find(".dn_username a").attr("href", url_user + arr_dn[i]["userid"]);
      node_dn.find(".dn_username_name").text(arr_dn[i]["username"]);
      node_dn.find(".dn_username_signature").text(arr_dn[i]["signature"]);

      // 摘要:超過 150 字就截斷
      var digest = "";
      var content = arr_dn[i]["content"];
      if (content.length > 150) {
        digest = content.substring(0, 150) + "... ";
      } else {
        digest = content;
      }
      node_dn.find(".dn_content_digest").text(digest);
      node_dn.find(".dn_content_text").text(content);
      node_dn.find(".dn_action_time").text(arr_dn[i]["posttime"]);

      // 點擊摘要:展開全文
      node_dn.find(".dn_content_digest").click(function () {
        var dn_right = $(this).parent().parent().parent();
        dn_right.find(".dn_content_text").toggle();
        dn_right.find(".dn_content_digest").toggle();
        dn_right.parent().find(".dn_content_close1").toggle();
        dn_right.parent().find(".dn_content_close2").toggle();
        dn_right.parent().find(".dn_action").toggle();
        var comm = dn_right.find(".dn_comm");
        if (comm.css("display") == "block") { comm.css("display", "none"); }
        return false;
      });

      // 點擊折疊
      node_dn.find(".dn_content_close2, .dn_content_close1").click(function () {
        var dn_right = $(this).parent().parent();
        dn_right.find(".dn_content_text").toggle();
        dn_right.find(".dn_content_digest").toggle();
        dn_right.parent().find(".dn_content_close1").toggle();
        dn_right.parent().find(".dn_content_close2").toggle();
        dn_right.parent().find(".dn_action").toggle();
        var comm = dn_right.find(".dn_comm");
        if (comm.css("display") == "block") { comm.css("display", "none"); }
        return false;
      });

      // 評論、分享、舉報的 hover 底線
      node_dn.find(".dn_action_comm, .dn_action_share, .dn_action_report").hover(
        function () { $(this).css("text-decoration", "underline"); return false; },
        function () { $(this).css("text-decoration", "none");      return false; }
      );

      // 點讚動畫
      node_dn.find(".dn_dianzan").click(function () {
        var dn_left  = $(this).parent();
        var zan_num  = dn_left.find(".dn_zannum span");
        var currzan  = zan_num.text();
        zan_num.text(parseInt(currzan) + 1);
        zan_num.animate({ fontSize: "1.2em" }, "fast");
        $(this).animate({ fontSize: "1.2em" }, "fast");
        zan_num.animate({ fontSize: "1em" }, "fast");
        $(this).animate({ fontSize: "1em" }, "fast");
        return false;
      });

      // 載入評論並處理評論項事件
      function load_comm(dn_id, dn_comm_items, flag) {
        $.ajax({
          url: "mockdata/commdata_" + dn_id,
          type: "get",
          dataType: "json",
          async: false,
          complete: function () { $("#load").hide(); },
          success: function (msg) {
            var encoded = $.toJSON(msg);
            var ret_code = $.evalJSON(encoded).code;
            var arr_dn   = $.evalJSON(encoded).data;
            if (ret_code == "200") {
              for (var i = 0; i < arr_dn.length; i++) {
                var n_comm = t_dn_comm.clone();
                n_comm.find(".dn_comm_id").attr("content", arr_dn[i]["ID"]);
                n_comm.find(".dn_comm_item_left a").attr("href", url_user + arr_dn[i]["userid"]);
                n_comm.find(".dn_comm_item_left img").attr("src", url_img + arr_dn[i]["avatar"]);
                n_comm.find(".dn_comm_item_middle_username a").attr("href", url_user + arr_dn[i]["userid"]);
                n_comm.find(".dn_comm_item_middle_username a span").text(arr_dn[i]["username"]);
                n_comm.find(".dn_comm_item_mid_content span").text(arr_dn[i]["content"]);
                n_comm.find(".dn_comm_foot_left span").text(arr_dn[i]["posttime"]);
                n_comm.find(".dn_comm_zannum span").text(arr_dn[i]["zan"]);

                // 評論項 hover 顯示回復/舉報
                n_comm.hover(function () {
                  $(this).find(".dn_comm_item_mid_action").toggle();
                });

                // 評論項點讚動畫
                var zan = n_comm.find(".dn_comm_dianzan");
                zan.click(function () {
                  var zan_num = $(this).parent().find(".dn_comm_zannum");
                  var currzan = zan_num.text();
                  zan_num.text(parseInt(currzan) + 1);
                  zan_num.animate({ fontSize: "1.2em" }, "fast");
                  $(this).animate({ fontSize: "1.2em" }, "fast");
                  zan_num.animate({ fontSize: "1em" }, "fast");
                  $(this).animate({ fontSize: "1em" }, "fast");
                  return false;
                });

                dn_comm_items.append(n_comm);
              }
            } else {
              alert(ret_code);
            }
          }
        });
      }

      // 載入熱門評論
      node_dn.find(".dn_action_comm").click(function () {
        var dn = $(this).parent().parent().parent().parent();
        dn.find(".dn_comm").toggle();
        var dn_comm_items = dn.find(".dn_comm_items");
        dn_comm_items.empty();
        load_comm(dn.find(".dn_id").attr("content"), dn_comm_items, 0);
        return false;
      });

      // 載入全部評論
      node_dn.find(".dn_comm_showall_button").click(function () {
        var dn = $(this).parent().parent().parent().parent();
        var dn_comm_items = dn.find(".dn_comm_items");
        dn_comm_items.empty();
        load_comm(dn.find(".dn_id").attr("content"), dn_comm_items, 1);
        return false;
      });

      layout_list.append(node_dn);
    }
  }

  function fill_list() {
    $.ajax({
      url: "mockdata/listdata",
      type: "get",
      dataType: "json",
      async: false,
      complete: function () { $("#load").hide(); },
      success: function (msg) {
        var encoded  = $.toJSON(msg);
        var ret_code = $.evalJSON(encoded).code;
        var arr_dn   = $.evalJSON(encoded).data;
        if (ret_code == "200") {
          render_dn_list(arr_dn);
        } else {
          alert(ret_code);
        }
      }
    });
  }

  // 載入更多
  $(".load_flag").click(function () {
    if (num <= maxnum) {
      fill_list();
      num++;
    } else {
      load_flag.find("#load_flag_info").css("display", "block");
      load_flag.find("#load_flag_button").css("display", "none");
    }
  });

  fill_list();
});

假資料格式

列表資料:

{
  "code": "200",
  "data": [
    {
      "ID":"1", "fid":"1212", "userid":"1001",
      "avatar":"images/user.png", "type":"閱讀注解",
      "from":"金剛經/第一品 法會因由分",
      "username":"用戶名", "signature":"用戶個性簽名",
      "digest":"內容摘要內容摘。要內容摘要,要內容要內容",
      "content":"時長老須菩提。在大眾中。即從座起……",
      "posttime":"2015-09-08 12:00:09", "zan":"100"
    },
    {
      "ID":"3", "fid":"1212", "userid":"1001",
      "avatar":"images/user.png", "type":"閱讀注解",
      "from":"金剛經/第一品 法會因由分",
      "username":"用戶名", "signature":"用戶個性簽名",
      "digest":"內容摘要內容摘。要內容摘要,要內容要內容",
      "content":"不於一佛二佛三四五佛而種善根……",
      "posttime":"2015-09-08 12:00:09", "zan":"100"
    }
  ]
}

評論資料:

{
  "code": "200",
  "data": [
    {
      "ID":"100001", "fid":"1212", "userid":"1001",
      "avatar":"images/user.png", "username":"用戶名",
      "content":"時長老須菩提。善付囑諸菩薩……",
      "posttime":"2015-09-08 12:00:09", "zan":"100"
    }
  ]
}

幾個值得檢討的地方

這個版本能跑,但寫法上有幾處如果重來我會改:

parent().parent().parent() 太脆弱:DOM 結構一動就全線出錯。應該在樣板根節點加上類別(例如 .dn_right),改用 $(this).closest(".dn_right") 表達意圖。

async: false 是效能殺手:同步 ajax 會鎖住整個瀏覽器 till 請求返回。改成非同步並把後續處理寫進 callback 即可。

$.evalJSON 已不建議使用:直接用 JSON.parse(),而若後端回傳正確的 Content-Type,jQuery 會自動解析,連呼叫都不必。

async:false 造成的連帶問題:在迴圈裡宣告 load_comm 這種函式,每次都會重新建立一次,應該提到迴圈外面。

整體來說,這個練習的價值在於把「樣板 clone + 事件委派 + 動畫回饋」這套動態列表的骨架走過一遍,剩下的就是把脆弱的地方逐步替換成現代寫法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved