1. 使用样式表
可以通过document.styleSheets属性访问文档中可用的CSS样式表,它会返回一组对象集合,这些对象代表了与文档管理的各个样式表。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>为DOM元素设置样式</title> <style title="core styles"> p {border: medium double green; background-color: lightgray;} #block1 {color: white;} table {border: thin solid red;border-collapse: collapse; margin: 5px;float: left;} td {padding: 2px;} </style> <link rel="stylesheet" type="text/css" href="css/style.css" /> <style media="screen AND (min-width:500px)" type="text/css"> #block2 {color: yellow;font-style: italic;} </style> </head> <body> <p id="block1"> 你承受的苦难并不比他人多太多,痛苦主要来自敏感和脆弱 </p> <p id="block2"> 一些年轻人,通过高端消费来营造自己高端收入的形象 </p> <div id="placeholder"></div> <script> var placeholder = document.getElementById("placeholder"); var sheets = document.styleSheets; for(var i= 0;i<sheets.length;i++){ var newElem = document.createElement("table"); newElem.setAttribute("border","1"); addRow(newElem,"Index",i); addRow(newElem,"href",sheets[i].href); addRow(newElem,"title",sheets[i].title); addRow(newElem,"type",sheets[i].type); addRow(newElem,"ownerNode",sheets[i].ownerNode.tagName); placeholder.appendChild(newElem); } function addRow(elem,header,value){ elem.innerHTML += "<tr><td>" + header + ":</td><td>" + value + "</td></tr>"; } </script> </body> </html>
时间: 2024-12-22 09:18:39