DIV CSS 佈局教程網

用 AngularJS + UI Router 製作帶動畫的多步表單向導
編輯:JavaScript綜合知識     

長表單是轉化率的殺手。把它拆成幾個步驟、配上進度指示與切換動畫,用戶的完成意願會明顯提高。本文用 AngularJS、UI Router 與 ngAnimate 三件套,做一個帶動畫的多步註冊向導。

技術選型

為什麼用 UI Router 而不是原生 ngRoute?因為它支持嵌套狀態:主表單是一個狀態,每個步驟是它的子狀態,子視圖會注入到主視圖預留的位置。這正好匹配「一個表單、多個步驟、共享同一份數據」的結構。

文件清單

- index.html           // 主布局
- form.html            // 表單容器 / 模板
- form-profile.html    // 第一步:個人資料
- form-interests.html  // 第二步:興趣選擇
- form-payment.html    // 第三步:支付確認
- app.js               // 應用、路由、控制器
- style.css            // 樣式與動畫

index.html:主布局

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

  <!-- CSS -->
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/darkly/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">

  <!-- JS:angular、ui-router、ngAnimate -->
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular-animate.min.js"></script>
  <script src="app.js"></script>
</head>

<!-- 應用我們的 angular app -->
<body ng-app="formApp">
  <div class="container">
    <!-- 視圖注入點 -->
    <div ui-view></div>
  </div>
</body>
</html>

app.js:路由與控制器

// app.js

// 創建應用,注入 ngAnimate 與 ui.router
angular.module('formApp', ['ngAnimate', 'ui.router'])

  .config(function ($stateProvider, $urlRouterProvider) {

    $stateProvider
      // 主狀態:顯示基礎表單
      .state('form', {
        url: '/form',
        templateUrl: 'form.html',
        controller: 'formController'
      })

      // 嵌套子狀態:各自的視圖
      // url 將是 /form/profile
      .state('form.profile', {
        url: '/profile',
        templateUrl: 'form-profile.html'
      })

      // url 將是 /form/interests
      .state('form.interests', {
        url: '/interests',
        templateUrl: 'form-interests.html'
      })

      // url 將是 /form/payment
      .state('form.payment', {
        url: '/payment',
        templateUrl: 'form-payment.html'
      });

    // 兜底路由:統一導向第一步
    $urlRouterProvider.otherwise('/form/profile');
  })

  .controller('formController', function ($scope) {
    // 所有表單數據集中存放
    $scope.formData = {};

    // 提交處理
    $scope.processForm = function () {
      // 這裡可以發起異步請求
      alert('awesome!');
    };
  });

注意狀態名的點號:form.profile 是 form 的子狀態。當路由匹配到子狀態時,UI Router 會先渲染父狀態的模板,再把子狀態的模板注入到父模板內的 ui-view 中。而 url: '/profile' 會自動拼接成 /form/profile。

form.html:表單容器

這個文件相當於「表單的模板」,其中的 ui-view 是子步驟的注入位:

<!-- form.html -->
<div class="row">
<div class="col-sm-8 col-sm-offset-2">

  <div id="form-container">

    <div class="page-header text-center">
      <h2>Let's Be Friends</h2>

      <!-- 步驟導航:使用相對路徑 -->
      <!-- ui-sref-active 會在狀態匹配時加上 active 類 -->
      <div id="status-buttons" class="text-center">
        <a ui-sref-active="active" ui-sref=".profile"><span>1</span> Profile</a>
        <a ui-sref-active="active" ui-sref=".interests"><span>2</span> Interests</a>
        <a ui-sref-active="active" ui-sref=".payment"><span>3</span> Payment</a>
      </div>
    </div>

    <!-- ng-submit 攔截提交 -->
    <form id="signup-form" ng-submit="processForm()">

      <!-- 子狀態視圖注入點 -->
      <div id="form-views" ui-view></div>

    </form>

  </div>

  <!-- 實時查看表單數據 -->
  <pre> {{ formData }} </pre>

</div>
</div>

兩個要點:一是 ui-sref=".profile" 用相對寫法引用子狀態,二是 ui-sref-active="active" 會在當前狀態與該鏈接對應時自動添加 active 類,進度條高亮不用寫一行 JS。

基礎樣式

/* style.css */

body { padding-top: 20px; }

#form-container {
  background: #2f2f2f;
  margin-bottom: 20px;
  border-radius: 5px;
}

#form-container .page-header {
  background: #151515;
  margin: 0;
  padding: 30px;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

/* 步驟按鈕 */
#status-buttons a {
  color: #FFF;
  display: inline-block;
  font-size: 12px;
  margin-right: 10px;
  text-align: center;
  text-transform: uppercase;
}
#status-buttons a:hover { text-decoration: none; }

/* 圓形數字 */
#status-buttons span {
  background: #080808;
  display: block;
  height: 30px;
  margin: 0 auto 10px;
  padding-top: 5px;
  width: 30px;
  border-radius: 50%;
}

/* 當前步驟變色 */
#status-buttons a.active span { background: #00BC8C; }

三個步驟視圖

<!-- form-profile.html -->
<div class="form-group">
  <label for="name">Name</label>
  <input type="text" class="form-control" name="name" ng-model="formData.name">
</div>

<div class="form-group">
  <label for="email">Email</label>
  <input type="text" class="form-control" name="email" ng-model="formData.email">
</div>

<div class="form-group row">
  <div class="col-xs-6 col-xs-offset-3">
    <a ui-sref="form.interests" class="btn btn-block btn-info">
      Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
    </a>
  </div>
</div>
<!-- form-interests.html -->
<label>What's Your Console of Choice?</label>
<div class="form-group">
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData.type" value="xbox" checked> I like XBOX
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" ng-model="formData.type" value="ps"> I like PS4
    </label>
  </div>
</div>

<div class="form-group row">
  <div class="col-xs-6 col-xs-offset-3">
    <a ui-sref="form.payment" class="btn btn-block btn-info">
      Next Section <span class="glyphicon glyphicon-circle-arrow-right"></span>
    </a>
  </div>
</div>
<!-- form-payment.html -->
<div class="text-center">
  <span class="glyphicon glyphicon-heart"></span>
  <h3>Thanks For Your Money!</h3>

  <button type="submit" class="btn btn-danger">Submit</button>
</div>

因為所有步驟共享同一個 formController 作用域,formData 在整個向導流程中天然保持,切換步驟不會丟數據。而「下一步」按鈕用 ui-sref 指向狀態名而非 URL,Angular 會自動生成正確的 href。

添加切換動畫

由於項目開始就加載了 ngAnimate,視圖進入離開時它會自動添加 ng-enter 與 ng-leave 類,我們只需寫 CSS:

/* ANIMATION STYLINGS */

#signup-form {
  position: relative;
  min-height: 300px;
  overflow: hidden;
  padding: 30px;
}

#form-views { width: auto; }

/* 進入與離開的基礎定位 */
#form-views.ng-enter,
#form-views.ng-leave {
  position: absolute;
  left: 30px;
  right: 30px;
  transition: 0.5s all ease;
  -moz-transition: 0.5s all ease;
  -webkit-transition: 0.5s all ease;
}

/* 進入動畫 */
#form-views.ng-enter {
  -webkit-animation: slideInRight 0.5s both ease;
  -moz-animation: slideInRight 0.5s both ease;
  animation: slideInRight 0.5s both ease;
}

/* 離開動畫 */
#form-views.ng-leave {
  -webkit-animation: slideOutLeft 0.5s both ease;
  -moz-animation: slideOutLeft 0.5s both ease;
  animation: slideOutLeft 0.5s both ease;
}

/* 動畫定義 */
@keyframes slideOutLeft {
  to { transform: translateX(-200%); }
}
@-moz-keyframes slideOutLeft {
  to { -moz-transform: translateX(-200%); }
}
@-webkit-keyframes slideOutLeft {
  to { -webkit-transform: translateX(-200%); }
}

@keyframes slideInRight {
  from { transform: translateX(200%); }
  to   { transform: translateX(0); }
}
@-moz-keyframes slideInRight {
  from { -moz-transform: translateX(200%); }
  to   { -moz-transform: translateX(0); }
}
@-webkit-keyframes slideInRight {
  from { -webkit-transform: translateX(200%); }
  to   { -webkit-transform: translateX(0); }
}

三個關鍵點:

  1. 絕對定位:讓離開與進入的視圖脫離文檔流,才能實現重疊切換,避免新視圖被舊視圖擠下去。
  2. min-height 與 overflow: hidden:給容器一個穩定高度並裁掉溢出部分,否則滑動過程中會撐開父容器或出現橫向滾動條。
  3. 把動畫掛在 ng-enter / ng-leave 上:這是唯一需要寫的「連接代碼」,其餘全交給 ngAnimate。

進一步完善的方向

這個向導能跑通基本流程,若要上生產,建議再補上:

  • 分步校驗。目前的「下一步」是純鏈接跳轉,用戶可以在必填项为空時直接跳過。可以給每個子狀態綁定獨立控制器,在 ui-sref 的點擊處理中先校驗當前步,通過後再跳轉。
  • 步驟狀態持久化。刷新頁面會回到第一步。可以把 formData 與當前步驟存入 $state 的 params 或本地存儲。
  • 提交狀態反饋。processForm 中應處理 loading、成功、失敗三種狀態,並在失敗時留在當前步。
  • 可訪問性:為步驟指示器加上 aria-current="step",讓屏幕閱讀器能告知用戶當前位置。
  • 尊重減少動效偏好:用 @media (prefers-reduced-motion: reduce) 關閉滑動動畫。

整體來看,UI Router 的嵌套狀態與 Angular 的數據綁定,讓「多步表單」這個傳統上頗為繁瑣的需求,變成了「定義幾個狀態 + 寫一點 CSS」的事。

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