练习一:编辑程序清单 13.1 的代码,修改其他一些样式属性,比如字体、元素边框、填充和对齐。
代码内容如下:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>设置页面的风格样式</title> <link > <style type="text/css"> span{ font-size: 16px; font-family: 黑体,arial,helvetica,sans-serif; padding: 20px; } </style> <script> function toogle(){ var myElement = document.getElementById("id1"); if(myElement.style.backgroundColor == 'red'){ myElement.style.backgroundColor = 'yellow'; myElement.style.color = 'black'; myElement.style.fontSize = '20px'; myElement.style.border = 'solid 5px green'; myElement.style.textAlign = 'center'; }else{ myElement.style.backgroundColor = 'red'; myElement.style.color = 'white'; myElement.style.fontSize ='30px'; myElement.style.border = 'dotted 5px green'; myElement.style.textAlign = 'right'; } } window.onload = function(){ document.getElementById("btn1").onclick = toogle; } </script> </head> <body> <span id="id1">欢迎回到我的站点</span> <input type="button" id="btn1" value="Toggle" /> </body> </html>
练习二:修改程序清单 13.4 的代码,让一些样式成为外部链接的,而不是包含在页面 <head> 区域的 <style> 和 </style> 标签里,观察是否会有不同的结果。
代码内容如下:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Switching styesheets with JavaScript</title> <style title="sheet1"> body{ background-color: navajowhite; color:red; } </style> <link rel="stylesheet" type="text/css" href="myCSS.css" title="sheet2" /> <style title="sheet3"> body{ background-color: pink; color:green; } </style> <script> function ssEnable(mySheet){ var change = false; var oldSheet = 0; for(var i=0;i<document.styleSheets.length;i++){ if(document.styleSheets[i].disabled == false){ oldSheet = i; } document.styleSheets[i].disabled = true; if(document.styleSheets[i].title == mySheet){ document.styleSheets[i].disabled = false; change = true; } } if(!change)document.styleSheets[oldSheet].disablesd = false; return change; } function sheet(){ var sheetName = prompt("请输入样式表的名称?"); if(!ssEnable(sheetName)){ alert("未能找到包含的原样式表。") } } window.onload = function () { document.getElementById("btn1").onclick = sheet; } </script> </head> <body> 点击按钮,输入并设置选择我的样式表<br /> <input type="button" id="btn1" value="手动输入式表" /> </body> </html>