問題出處:http://stackoverflow.com/quest......xt-color-based-on-background-color-using-css
常見的進度條上除了進度條顏色之外,上面若有文字時,也會有文字顏色來做反差顯示用。但若進度條的進度只有一半時,那文字文色的反差是要依什麼為主呢?
如何讓同一進度條上的文字顏色依所在的背景顏色而改變就是一個有趣的問題
而 Jakub 就用了 CSS 的方式來解決它。
檢視原始碼 HTML
1 2 3 4 5 6 7 8 | <body> <div style="position: relative; width: 250px; background: white; border: 1px solid #000; color: #000;"> <div style="position: absolute; z-index: 10; overflow: hidden; width: 105px; background-color: navy; white-space:nowrap; color: #FFF;"> Between 4:00 and 6:00 blah blah </div> Between 4:00 and 6:00 blah blah </div> </body> |
利用了區塊重疊及 overflow 的特性就能輕鬆了達到效果。
不過因為他只是為了回答而用了內嵌的樣式,所以我就稍微改一下讓 jQuery 能自動幫你算出相對應比例的寬度:
檢視原始碼 JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | <style type="text/css"> .progressbar { position: relative; width: 250px; background: #fff; border: 1px solid #000; color: #000; margin-bottom: 10px; } .inprogress { position: absolute; z-index: 10; overflow: hidden; background-color: #000080; white-space: nowrap; color: #fff; } </style> <script type="text/javascript"> $(function(){ // 把每一個進度條進行處理 $('.progressbar').each(function(){ // span 中的數值為進度值 // 並取出 .progressbar 中除了 span 進度的文字 var $this = $(this), _width = $this.width(), $span = $this.find('span'), _val = $this.find('span').text(), _text = $this.clone().find('span').remove().end().text(); // 把 span 加上 .inprogress 樣式並依值來設定寬度 $span.addClass('inprogress').width(_width / 100 * _val).text(_text); }); }); </script> <body> <div class="progressbar"> <span>4</span> 白海豚會自己轉彎 </div> <div class="progressbar"> <span>70</span> 我的選票會轉彎 </div> </body> |
span 中的值為進度條的進度值,利用它跟整個進度條的寬度來計算就能求出 span 該設定的寬度囉。