DIV CSS 佈局教程網

用 Vue.js 做一個會「走動」的 Bootstrap 進度條
編輯:關於JavaScript     

Bootstrap 內建的進度條樣式相當美觀,本文要進一步讓它「動」起來:每次點擊按鈕,進度條就往前推一段,搭配內建的 active 條紋動畫,看起來就像在持續走動。過程中還會順帶認識 Vue.js 的 v-bind:style 內聯樣式綁定。

1. 頁面效果

起始位置:

點擊「走」按鈕後:

2. HTML 程式碼

 <div> <div class="progress progress-striped active"> <div class="progress-bar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" v-bind:style="progressStyle">進度條</div> </div> <button type='button' v-on:click='queryEnterprise' class='btn btn-primary'>走</button> </div> 

這裡的關鍵是 v-bind:style="progressStyle",也就是綁定內聯樣式。順帶複習 v-bind:style 的幾種語法:

a. 物件語法:看起來像 CSS,其實是個 JavaScript 物件,屬性名可用駝峰式或短橫分隔命名:

 <div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div> 
 data: { activeColor: 'red', fontSize: 30 } 

直接綁定到一個樣式物件通常更好,能讓模板更清晰:

 <div v-bind:style="styleObject"></div> 
 data: { styleObject: { color: 'red', fontSize: '13px' } } 

b. 陣列語法:可將多個樣式物件套用到同一元素:

 <div v-bind:style="[styleObjectA, styleObjectB]"> 
 data: { styleObjectA: { color: 'red' }, styleObjectB:{ fontSize: '13px' } }

c. 自動添加前綴:當使用需要廠商前綴的屬性(如 transform)時,Vue.js 會自動偵測並加上對應前綴。

3. JS 程式碼

 <script> export default { components:{}, props:{}, ready:function(){}, computed:{}, methods:{ queryEnterprise:function(){ if(parseInt(this.progressStyle.width)<100){ this.progressStyle.width=parseInt(this.progressStyle.width)+30+'%'; }else{ alert("進度條已經走完"); } } }, data () { return { //進度條樣式 progressStyle:{ width:'10%', }, } }, } </script> 

點擊時,queryEnterprise 會把 progressStyle.width 增加 30%,直到滿 100% 再提示已完成。

4. 樣式

 .progress { height: 40px; transition: 3s; } .progress-bar { font-size: 16px; line-height: 40px; } 

這裡的 transition: 3s 讓寬度變化有了平滑的過渡動畫,搭配 Bootstrap 的 active 條紋,就呈現出「走動中」的視覺效果。

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