2016-06-28 81 views
3

我發現的所有其他問題都與更改特定元素有關,或者使用按鈕更改CSS文件,但我期望找到的是:刷新整個CSS文件

有一個腳本可以在頁面刷新時交換整個CSS文件?

I.e.我有我的核心style.css和補充{color}.css文件,它替換style.css中的某些元素,我希望這些補充CSS文件在刷新時隨機加載。

對不起,我甚至不知道從哪裏開始。希望有人能提供一些建議?

謝謝。

回答

3

從根本上說,這只是一個隨機的,如撿東西的事:(一罕見的情況下,document.write實際上不是一個壞的解決方案)

<head> 
<!-- ... --> 
<script> 
var sheets = ["sheet1.css", "sheet2.css", "sheet3.css"]; 
var sheet = sheets[Math.floor(Math.random() * sheets.length)]; 
document.write('<link rel="stylesheet" href="' + sheet + '">'); 
</script> 
<noscript> 
<link rel="stylesheet" href="sheet1.css"> 
</noscript> 
<!-- ... --> 

注意noscript後備總是會使用JavaScript禁用的瀏覽器上的樣式表相同。

+1

包括幹得好了'

+0

完美。非常感謝你! – ukijake

1

所有你需要做的用Javascript加載CSS文件是將一個<link>元素添加到DOM/body,它會自動加載。

因此,在您<head>部分,您可以包括<script>標籤,只是隨機選擇一個數組color.css並生成鏈接標籤,最好儘早文件,以防止閃爍英寸

<script> 
    var colors = ['red.css', 'blue.css', 'green.css']; 
    var colors_idx = Math.floor(Math.random()*colors.length); 

    document.write('<link href="'+colors[ colors_idx ]+'" rel="stylesheet" type="text/css" />'); 
</script> 

(PS。有簡潔的方式來注入HTML,保持簡潔把重點放在解決方案。用你喜歡的方式,document.write可有點善變。)