2013-04-16 58 views
3

我有一個網站的顏色主題,我正在處理刷新上的更改,並希望在我的HTML中顯示CSS背景顏色屬性。那可能嗎?在HTML中嵌入CSS屬性

<footer>The color of the moment is <insert the background color attribute>. Refresh for a makeover</footer> 

會顯示類似

「的那一刻的顏色爲#DB0C0C。刷新了改頭換面」

由於十六進制顏色變化基於樣式表加載,我不想硬編碼它。如果我有一個Ruby變量@color其中=#FF0000,想在HTML中顯示它我可以做類似

<%= @color%> 

我不知道是否有任何方式做類似的訪問CSS屬性的東西。

+0

是有一些原因,你不能只寫它? – Daedalus

+0

因爲它變化 – bsiddiqui

+2

然後根據你的編輯,你需要的是JavaScript。沒有純粹的css/html方式來獲得該值,否則。 – Daedalus

回答

2

你甚至不需要jQuery的這個..你可以只使用香草JavaScript和.getComputedStyle()

<span id='color-map'></span> 

var element = document.getElementById("id-goes-here"); 
var style = window.getComputedStyle(element); 

document.getElementById('color-map').innerHTML = style.backgroundColor; 

然而,這樣看來,這並沒有給顏色爲十六進制,而是一個'rpg(x,y,z)'字符串。要獲得從十六進制,你可以使用正則表達式分析它,並返回結果:

function rgbsToHex(str) { 
    var hex = "#"; 
    var matches = str.match(/rgb\((\d+),\s(\d+),\s(\d+)\)/); 
    hex += Number(matches[1]).toString(16); 
    hex += Number(matches[2]).toString(16); 
    hex += Number(matches[3]).toString(16); 
    return hex; 
} 

DEMO

0

您可以在jQuery中使用.css()函數。

$('footer').find('span').text($('.bg').css('background-color')); 

這會給你的顏色RGB,如果你想顯示其在HEX然後檢查this獲取更多信息。