DIV CSS 佈局教程網

Bootstrap 打造微信手機端頁面:從模態框到列表頁的完整實作
編輯:JQuery入門技巧     

用 Bootstrap 做微信內的手機網頁,最大的好處是幾乎不用碰排版細節:網格、表單、模態框、表格樣式全部現成,你只要專心處理資料流。本文以一個「物料出/入庫」與「安全/質量填報」的實際專案為例,把常用元件一次串起來。

一、基本骨架:視窗與整行寬度

手機端最關鍵的一行是 viewport 設定,它關閉了縮放,讓版面以裝置真實寬度渲染:

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />

而佔滿一整行的容器就是:

<div class="col-md-12"></div>

二、模態框(Modal)承載表單

手機螢幕小,不適合跳頁。把「出庫」這種次要操作放進模態框是最順的做法。以下範例使用 Spring 的 <spring:form> 標籤,並在數量欄位旁加上增減按鈕:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h4 class="modal-title" id="myModalLabel">出庫信息</h4><br>
  </div>
  <div class="modal-body">
    <spring:form id="outMaterialForm" action="" class="form-horizontal" modelAttribute="outMaterialDto">
      <spring:hidden path="mId"/>
      <div class="form-group">
        <label class="col-sm-2 control-label">出庫時間:</label>
        <div class="col-sm-4">
          <spring:input class="form-control" path="outDate" readonly="true" placeholder="請選擇時間"
            data-bv-notempty="true" data-bv-notempty-message="不能為空"/>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">出庫數量:</label>
        <div class="col-sm-4">
          <div id="1" class="input-group input-group-option quantity-wrapper">
            <span class="input-group-addon quantity-remove btn"><span class="glyphicon glyphicon-minus"></span></span>
            <spring:input id="1inp" value="6" path="outQuantity" name="option[]" class="form-control quantity-count" />
            <span class="input-group-addon quantity-add btn"><span class="glyphicon glyphicon-plus"></span></span>
          </div>
        </div>
      </div>
      <div class="form-group">
        <label class="col-sm-2 control-label">出庫人:</label>
        <div class="col-sm-4"><spring:input class="form-control" path="outLeader"/></div>
      </div>
    </spring:form>
  </div>
  <div class="modal-footer" style="text-align: center;">
    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
    <button type="button" class="btn btn-primary" id="saveOutMaterialBtn">保存</button>
  </div>
</div>
</div>
</div>

三、頁面主體:資料展示 + 表格

頁面頭部需要引入的資源順序如下,注意 jQuery 一定要在 Bootstrap 之前:

<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="<%=basePath%>/page/pf/base/bootstrap/table/bootstrap-table.css" rel="stylesheet"/>
<link href="<%=basePath%>/page/pf/base/bootstrap/bootstrap-datetimepicker.min.css" rel="stylesheet"/>

<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="https://cdn.bootcss.com/bootstrap-table/1.9.1/bootstrap-table.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-table/1.9.1/locale/bootstrap-table-zh-CN.min.js"></script>
<script src="<%=basePath%>/page/pf/base/bootstrap/bootstrap-datetimepicker.min.js"></script>
<script src="<%=basePath%>/page/pf/base/bootstrap/bootstrap-datetimepicker.zh-CN.js"></script>

主體用 form-horizontal 做左右對齊的資料列表,再用 bootstrap-table 畫出庫紀錄:

<body class="container">
<h4 class="page-header">詳細</h4>
<div style="text-align: right;">
  <button type="button" id="outQuantityBtn" class="btn btn-primary">出庫</button>
</div>

<spring:form id="defaultForm" class="form-horizontal" modelAttribute="materialDto">
<input type="hidden" id="id" value="${materialDto.id }"/>
<div class="form-group">
  <label class="col-sm-2 control-label">項目名稱:</label>${materialDto.projectName }
</div>
<div class="form-group">
  <label class="col-sm-2 control-label">物料名稱:</label>${materialDto.name }
</div>
<div class="form-group">
  <label class="col-sm-2 control-label">入庫時間:</label>${materialDto.inDate }
</div>
<div class="form-group">
  <label class="col-sm-2 control-label">物料數量:</label>${materialDto.inQuantity }
</div>
<table class="table table-hover table-bordered" id="outMaterialTable"
  data-toggle="card" data-card-view="true" data-show-columns="false">
  <caption>出庫列表</caption>
  <thead>
  <tr>
    <th data-field="outDate" data-halign="center">出庫時間:</th>
    <th data-field="outQuantity" data-halign="center">出庫數量:</th>
    <th data-field="outLeader" data-halign="center">出庫人:</th>
  </tr>
  </thead>
  <tbody></tbody>
</table>
</spring:form>

另外還準備了兩個「提示型」模態框,一個顯示「正在保存,請稍後」,一個顯示「保存成功」。這種做法比 alert() 友善得多,也不會打斷使用者的操作節奏。

四、JavaScript:表格初始化與互動

var MaterialManager = {};

$(document).ready(function() {

  MaterialManager.query = function(){
    $('#outMaterialTable').bootstrapTable('destroy');   // 先銷毀,避免重複渲染
    $("#outMaterialTable").bootstrapTable({
      url: '../../supManage/material/queryOutMaterialList.do',
      method: "get",
      contentType: "application/x-www-form-urlencoded",
      striped: true,
      sidePagination: "server",       // 服務端分頁
      queryParamsType: "undefined",   // 取得 pageNumber / pageSize
      queryParams: function queryParams(params) {
        return {
          currentPage: params.pageNumber,
          recordsPerPage: params.pageSize,
          mId: $("#id").val()
        };
      }
    });
  };
  MaterialManager.query();

  // 保存
  $("#saveOutMaterialBtn").click(function(){
    $("#loadingModal").modal('show');
    $("#myModal").modal('hide');
    $.ajax({
      type: "POST",
      url: "../../supManage/material/saveOutMaterial.do",
      data: $("#outMaterialForm").serialize(),
      dataType: "json",
      success: function(data){
        $("#loadingModal").modal('hide');
        $("#alertModal").modal('show');
        MaterialManager.query();
        setInterval(function(){ $("#alertModal").modal('hide'); }, 2000);
      }
    });
  });

  // 打開出庫模態框
  $("#outQuantityBtn").click(function(){ $("#myModal").modal('show'); });

  // 日期選擇器
  $('#outDate').datetimepicker({
    format: 'yyyy-mm-dd hh:ii:ss',
    language: 'zh-CN',
    autoclose: true
  });

  // 數量增
  $(".quantity-add").click(function(){
    var elemID = $(this).parent().attr("id");
    $("#" + elemID + 'inp').val(parseInt($("#" + elemID + 'inp').val()) + 1);
  });

  // 數量減
  $(".quantity-remove").click(function(){
    var elemID = $(this).parent().attr("id");
    $("#" + elemID + 'inp').val(parseInt($("#" + elemID + 'inp').val()) - 1);
  });
});

五、手機拍照上傳

微信環境下最實用的一招,是在 <input type="file"> 加上 accept="image/*",點下去就會直接開啟相機或相簿:

<a href="javascript:void(0);" class="file">
  <img alt="" src="<%=basePath%>/page/project/wechat/m500point/img/camera_picture.png">
  <input type="file" name="sSecurityFile" accept="image/*" onchange="changeFile(this,'sSecurityFile');">
</a>

搭配的 CSS 把真正的 file input 透明化鋪在圖片上,使用者看到的就只是一顆相機圖示:

.file { position: relative; display: inline-block; overflow: hidden; }
.file input { position: absolute; font-size: 100px; right: 0; top: 0; opacity: 0; }
.file:hover { background: #AADFFD; border-color: #78C3F3; color: #004974; }

而「查看已上傳的圖片」則用另一顆圖示觸發模態框:

function showPicture(attenchmentId){
    if (!attenchmentId) return;
    $("#modelPicture").attr("src", "../../attachment/displayjpg.do?attenchmentId=" + attenchmentId);
    $("#myModal").modal('show');
}

填報表單本身 consists of 兩張 table:securityTable 放安全檢查項(安全施工、文明施工、腳手架、基坑支撐、外用電梯、施工用電、施工機械),qualityTable 放質量檢查項(石灰質量、水泥質量、樁的數量與布置、材料配合比、施工工藝、樁的密實度、地基承載力)。每一列都是「項目名稱 + 得分輸入框 + 是否合格單選 + 拍照上傳」的結構,寫法完全一致,只要複製貼上改欄位名即可。

六、列表頁

列表頁更簡單,一張 bootstrap-table 加上一個自訂的「詳細」欄:

<table class="table table-hover" id="pointQualitySecurityTable"
  data-toggle="card" data-card-view="true" data-show-columns="true">
  <input type="hidden" id="pId" value="${pointQualitySecurityDto.pId }"/>
  <thead>
  <tr>
    <th data-field="pointProject" data-halign="center">工程部位(工點):</th>
    <th data-field="recordPerson" data-halign="center">記錄人:</th>
    <th data-field="recordDate" data-halign="center">記錄時間:</th>
    <th data-field="checkType" data-halign="center">檢查類型:</th>
    <th data-field="sId" data-visible="false"></th>
    <th data-field="qId" data-visible="false"></th>
    <th data-field="ck" data-halign="center" data-formatter="showDetail">詳細:</th>
  </tr>
  </thead>
  <tbody></tbody>
</table>
function initTable() {
    $("#pointQualitySecurityTable").bootstrapTable({
        method: "get",
        url: "queryQualitySecurityList.do",
        contentType: "application/x-www-form-urlencoded",
        striped: true,
        pagination: false,
        sidePagination: "server",
        queryParamsType: "undefined",
        queryParams: function (params) {
            return { pageNumber: params.pageNumber, pId: $("#pId").val() };
        }
    });
}

// 用 data-formatter 產生「查看」連結,順便把 sId / qId 帶過去
function showDetail(value, row, index){
    return "<a href='toQualitySecurityViewPage.do?sId=" + row.sId + "&qId=" + row.qId + "'>查看</a>";
}

$(document).ready(function(){ initTable(); });

幾個容易踩到的坑

bootstrap-table 重新初始化前一定要 destroy。否則第二次查詢時表頭會重複渲染,越疊越亂。

手機端要慎用固定寬度的欄位。col-sm-2 這種左側標籤欄在手機上很窄,實務上可以改用 col-xs-* 覆寫,或乾脆讓標籤改放上排。

拍照上傳後要記得回到原本的捲動位置。範例中把 scrollTop 存進隱藏欄位,回來再用 window.scrollTo() 還原,這個細節對長表單的體驗影響很大。

整體來說,Bootstrap 在微信場景的價值在於「快速把一個能用的後台搬到手機上」。若追求更貼近原生 App 的操作手感,再考慮 WeUI、Vant 這類專門的行動端元件庫會更合適。

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