舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function run() { var ss = document.styleSheets; var s = document.getElementById( "show" ); var i, c; for (i = 0; i < ss[0].cssRules.length; i++) { c = document.createElement( "li" ); c.innerHTML = ss[0].cssRules[i].cssText; s.appendChild(c); } } /* 《程式語言教學誌》的範例程式 檔名:document030.js 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2011 年 8 月 */ |
此例先取得樣式表的集合物件
2 | var ss = document.styleSheets; |
然後利用迴圈 (loop) ,將樣式表中的所有規則 (rule) 顯示在網頁之中
5 6 7 8 9 | for (i = 0; i < ss[0].cssRules.length; i++) { c = document.createElement( "li" ); c.innerHTML = ss[0].cssRules[i].cssText; s.appendChild(c); } |
我們在此例中的 CSS 樣式表為外連的檔案,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | .demo 1 { font-size : 0.5em ; } .demo 2 { font-size : 4em ; } /* 《程式語言教學誌》的範例程式 檔名:example3.css 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2011 年 8 月 */ |
然後以下面的 HTML 文件載入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!DOCTYPE html> < html > < head > < title >HTML DOM DEMO</ title > < link type = "text/css" rel = "stylesheet" title = "example3" href = "example3.css" /> < script src = "document030.js" type = "text/javascript" ></ script > </ head > < body > < div class = "demo2" >There is no spoon.</ div > < input type = "button" value = "RUN" onclick = "run();" > < div >Style Sheet: < ul id = "show" ></ ul ></ div > </ body > </ html > <!-- 《程式語言教學誌》的範例程式 檔名:document030.html 功能:示範 JavaScript 程式 作者:張凱慶 時間:西元 2011 年 8 月 --> |
瀏覽器 (broswer) 開啟,按下 RUN 後的結果如下

中英文術語對照 | |
---|---|
樣式表 | style sheet |
物件 | object |
迴圈 | loop |
規則 | rule |
瀏覽器 | broswer |
您可以繼續參考
基本概念
文件物件 document
- 屬性
- document.activeElement
- document.alinkColor
- document.anchors
- document.bgColor
- document.cookie
- document.documentElement
- document.documentURI
- document.forms
- document.images
- document.inputEncoding
- document.lastModified
- document.lastStyleSheetSet
- document.linkColor
- document.links
- document.location
- document.plugins
- document.preferredStyleSheetSet
- document.readyState
- document.referrer
- document.selectedStyleSheetSet
- document.styleSheets
- document.styleSheetSets
- document.title
- document.URL
- document.vlinkColor
- 方法
- document.close()
- document.createAttribute(name_str)
- document.createElement(element_str)
- document.createTextNode(text_str)
- document.enableStyleSheetsForSet(ss_str)
- document.getElementById(id_str)
- document.getElementsByClassName(cn_str)
- document.getElementsByName(n_str)
- document.getElementsByTagName(tn_str)
- document.hasFocus()
- document.open()
- document.write(str)
- document.writeln(str)
相關目錄
HTML DOM 快速導覽
JavaScript 教材
首頁
參考資料
https://developer.mozilla.org/en/DOM/document.styleSheets
https://developer.mozilla.org/en/DOM/stylesheet
https://developer.mozilla.org/en/DOM/CSSStyleSheet
https://developer.mozilla.org/en/DOM/CSSRuleList
https://developer.mozilla.org/en/DOM/cssRule
http://www.w3.org/TR/DOM-Level-2-Style/stylesheets.html#StyleSheets-DocumentStyle-styleSheets
沒有留言:
張貼留言