使用 .stop() 讓動畫效果更滑順

使用 jQuery 的 .stop() 語法,就可以讓動畫效果更滑順

點擊按鈕,.box會收合,希望在收合的「過程中」,再次點擊按鈕就馬上變為「展開」(會立刻中斷目前正在收合的動畫),該怎麼做呢?

html語法:

jquery語法:

使用.stop()中斷目前的動畫效果,接著跑下一個動畫

[注意!]

stop() 括弧裡面不能填寫時間(填入後是沒有差異的)

就完成了!

Q&A

Q:

請問jQuery有辦法使用按鈕讓div左右縮放嗎?

A:

jQ 有 animate 的語法,可以再操控該元素來移動。或是切換 toggleClass 進行 margin-left、right 移動,再搭配 CSS3 transition 的特性也 ok

動畫中止再啟動

Q:

除了stop()這個一半中斷的效果,我想問有沒有跑到一半,讓它停在那裡,除非你再按一次,它才會繼續動作的指令。

A:

如果使用 stop 停止,還可以用 animated 讓它繼續唷

這邊有提供一個範例,你可以參考
https://codepen.io/saffranwang/pen/eXBxOv

1
2
if ($('.box').is(':animated')) {
    $('.box').stop();

:animated 是 jQuery 的動畫選取器,可以用來判斷元素是否在動畫狀態

https://api.jquery.com/animated-selector/

  • 在範例中原本是將 “執行動畫 (Animated)” 和 “停止動畫 (Stop)”  這兩個需求分為兩個按鈕

而 一個按鈕滿足兩個需求 是指用 “One Button” 這一個按鈕來達成執行與停止兩個需求

這邊這個程式碼的意思是,當點下 .one 按鈕時,先去判斷 .box 的狀態:

如果 .box 正在執行動畫,就讓 .box 停止

  • else 也就是當不符合上面的條件就執行 else 的內容,讓 .box 由左往右移動。

+=600 代表向右移動600px

10000 代表整個動畫會花費10000毫秒

[if用法]

https://www.w3schools.com/js/js_if_else.asp

  • ( )小括弧裡面寫「條件」
  • { }大括弧裡面寫「如果條件為真,就要執行的程式碼」
1
2
3
if (condition) {
// block of code to be executed if the condition is true
}

[else用法]

Use the else statement to specify a block of code to be executed if the condition is false.

1
2
3
4
5
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

[else if用法]

Use the else if statement to specify a new condition if the first condition is false.

1
2
3
4
5
6
7
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

#動畫中止再啟動(我的codepen練習)

使用 .on()
https://codepen.io/saffranwang/pen/jJVdPq

使用 .click()
https://codepen.io/saffranwang/pen/aMJNyV

重點一

Q:

在css語法中,為什麼 .box 必須使用 position: relative; ,我把它拿掉的話,就無法做出動畫效果了

A:

因為這個 box 的移動是以指定位置來做移動,所以要設定 position: relative 讓 box 可以被指定定位

重點二

在jquery語法中,使用 .on() 或是 .click() 都是可以達到相同效果的

重點三

Q:

在jquery語法中,同樣都是.animate()語法,為什麼在我的練習中,left後面的數值要用單引號包起來?(下圖綠色箭頭處)

但是這裡scrollTop後面的數值就不用加單引號呢?

A:

其實傳進去的數值是代表 700px,也就是 left: 700px,雖然說 JQuery 函式裡面會幫我們處理 700, '700' 這類的寫法 ,程式能讀得懂能支援,但必須要理解這個數值的用途是什麼。

所以這樣的寫法其實也沒為什麼,程式設計就這樣,有支援這種寫法就可以用,沒支援就不行。

重點四

Q:

在這篇說明文章中,.animate()的語法是

(selector).animate({styles},speed,easing,callback)

其中 {styles} 這個參數可以填入的值如下圖紅色框框列出,但是並沒有scrollTop呀,那為什麼可以使用呢?

A:

你給的說明文章中是針對 CSS 有提供的 style 屬性所做的動畫效果,不過其實列出的也不是全部,建議要了解的話還是看 JQuery 官方的文件比較新也比較正確: 連結

文件裡面有提到:

In addition to style properties, some non-style properties such as scrollTop and scrollLeft, as well as custom properties, can be animated.

除此之外也要看你使用 JQuery 版本,每個版本所提供的 API 也不完全一樣。