透過 document.styleSheets[0].disabled 屬性,可以在執行時動態啟用或停用頁面中的第一份樣式表,是實現主題切換或臨時關閉樣式的簡便做法。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>停用樣式表示範</title>
<style>
.a { background:blue; border:1px solid green; }
</style>
</head>
<body>
<input type="text" class="a"
onfocus="document.styleSheets[0].disabled=true">
</body>
</html>
當輸入框獲得焦點(onfocus)時,程式將 styleSheets 集合中的第一份樣式表設為 disabled=true,此時套用 class="a" 的藍色背景與綠色邊框便會失效。若把 disabled 改回 false,則樣式會重新生效。
這個技巧常用於:切換高對比或無障礙版本、暫時關閉動畫樣式、除錯時快速隔離某份 CSS 的影響等。索引 0 代表頁面中載入的第一份樣式表,若有多份樣式表,可調整索引值來控制不同的檔案。