jQuery .animate() backgroundColor 未顯示及反應很慢問題

最近因為支援公司 Art (其實是不想面對繁複的功能需求)切版工作,久沒碰有點生疏,幸好還做的出來。

我要做一個捲動網頁,選單背景會變色的動畫效果,採用 jQuery 的 .animate(),所以我寫出以下程式:
<script type="text/javascript">
    $(function() {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 113) {
                $('header').animate({
                    backgroundColor: "#23485B"
                }, 600);
            } else {
                $('header').animate({
                    backgroundColor: "transparent"
                }, 300);
            }
        }).trigger('scroll');
    });
</script>

這時捲動網頁是不會有任何改變的,因為缺少 jQuery color,所以多載入 jQueryUI。
<script src="{{ asset('js/jquery-ui.min.js') }}"></script>
<script type="text/javascript">
    $(function() {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 113) {
                $('header').animate({
                    backgroundColor: "#23485B"
                }, 600);
            } else {
                $('header').animate({
                    backgroundColor: "transparent"
                }, 300);
            }
        }).trigger('scroll');
    });
</script>

現在捲動網頁選單可以正確顯示顏色的變化,可是多捲動幾次就會發現動畫效果很慢才會出現,這是為什麼呢?

原來因為每次捲動都會觸發動畫,而動畫是需要時間去反應的,多次的捲動就需要多次的動畫時間,所以後面動畫反應就會越來越慢。

我們可以在 .animate() 之前加上 .stop(),來停止該物件前面的動畫,如此一來當下的動畫就可以馬上看到效果。
<script src="{{ asset('js/jquery-ui.min.js') }}"></script>
<script type="text/javascript">
    $(function() {
        $(window).scroll(function() {
            if ($(this).scrollTop() > 113) {
                $('header').stop().animate({
                    backgroundColor: "#23485B"
                }, 600);
            } else {
                $('header').stop().animate({
                    backgroundColor: "transparent"
                }, 300);
            }
        }).trigger('scroll');
    });
</script>

留言