DIV CSS 佈局教程網

jQuery 做顏色漸變:animate() 不支持 color,該怎麼辦
編輯:JQuery入門技巧     

這是一個容易撞牆的細節:jQuery 的 animate() 不能處理非數值型 CSS 屬性。

 // 以下兩種寫法都不會生效
 // .animate({ color:'red' }, 500)
 // .animate({ fontWeight:'bold' }, 500)

原因是 animate 依靠數值插值來逐幀計算中間狀態,而顏色和字重並不是簡單的數字。想做出顏色漸變,只能繞道而行。下面給兩種思路。

方法一:雙層疊加 + fadeIn 模擬

思路很樸素:準備一個與原元素位置完全重合、顏色不同的副本並隱藏,懸浮時讓副本漸顯,視覺上就形成了顏色過渡。

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script type="text/javascript" src="https://libs.baidu.com/jquery/1.7.2/jquery.js"></script>
 </head>
 <body>
 <div class="b1" style="font-size: 50px;font-weight: bold;position: absolute;">BBB</div>
 <div class="b2" style="font-size: 50px;font-weight: bold;position: absolute;color: #f60;display: none;">BBB</div>
 </body>
 <script type="text/javascript">
 $(function(){
   $('.b1').hover(function(){
     $('.b2').fadeIn(500);
   })
 })
 </script>
 </html>

缺點顯而易見:兩個元素的樣式必須嚴格一致,改起來要改兩處;而且副本會佔據 DOM。這種「笨方法」適合只想要個效果、樣式固定不變的場景。

方法二:交給 CSS3 transition

既然 jQuery 做不了,不如讓瀏覽器自己來。CSS3 的 transition 天生支持顏色插值,代碼量少得多,性能也更好(合成層由瀏覽器優化)。

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8">
 <title>Document</title>
 <style type="text/css">
 div{
   color: red;
   transition: color 1s;
 }
 div:hover{
   color: yellow;
 }
 </style>
 <script type="text/javascript" src="d:/jquery-3.1.0.js"></script>
 </head>
 <body>
 <div class="wrapper">1111</div>
 <script type="text/javascript">
 </script>
 </body>
 </html>

這裡甚至完全沒用到 jQuery。如果還需要「點擊後渐变」而非「懸浮後漸變」,可以用 jQuery 切換 class,再由 CSS 承擔動畫:

 $('#btn').click(function(){
   $('div').toggleClass('changed');
 });

選型建議

優先用 CSS3 transition,程式碼更短、效能更好,也更容易維護。只有在必須兼容不支持 transition 的老舊 IE 時,才退回方法一這種疊加模擬的方案。另外若項目裡已經引入了 jQuery UI 或 jQuery Color 插件,它們為 animate() 補上了顏色插值能力,也可以直接 .animate({ backgroundColor: '#f60' }),但這無疑增加了頁面負擔。

相關工具推薦

在線特效文字/彩色文字生成工具:
https://tools.jb51.net/aideddesign/colortext

在線彩虹文字/顏色漸變文字生成工具:
https://tools.jb51.net/aideddesign/txt_caihongzi

在線發光字生成工具:
https://tools.jb51.net/aideddesign/txt_faguangzi

仿古書排版文字豎排轉換工具:
https://tools.jb51.net/transcoding/shupai

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