二十五、理解DOM
DOM(Document Object Model, 文档对象模型)把JavaScript 和 HTML 文档的内容联系了起来,通过使用DOM我们能够添加、移除和操作各种元素,还可以使用事件来响应用户的交互操作,以及完全控制CSS样式。
DOM是一组对象的集合,这些对象代表了HTML文档里的各个元素。顾名思义,DOM就像一个模型,它由代表文档的众多对象组成。DOM是Web开发的关键工具之一,它是HTML文档结构内容与JavaScript之间桥梁。
浏览器会解析HTML文档,并创建一个DOM模型,这个模型中保存着各个HTML元素之间的层级关系 ,每个元素即是一个JavaScript对象。我们可以通过DOM来获取文档信息并对其进行修改,这是现代Web应用程序的基础。DOM模型里的每一个对象都有若干属性和方法,当你用它们来修改对象的状态时,浏览器会让这些改动反映到对应的HTML元素上,并更新这个HTML文档。
DOM Level(DOM等级)是其标准化过程中的版本号。我们有多种方式来解决DOM功能的多变性进而消除浏览器之间实现方式的差异,比如使用 jQuery库。
常用的DOM对象有 Document对象、Location对象、Window对象、History对象、Screen对象、HTMLElement对象、Text对象、CSSStyleDeclaration对象、DOM事件对象等。
二十六、Document对象
使用 Document对象:
<p id="pid1" class="pid">‘Family’, in my opinion.</p>
<p id="pid2" class="pid">The six letters of the word ‘family’ are just like the six surfaces of a cube. </p>
<script>
document.writeln("<pre>URL:"+document.URL);
var oP = document.querySelectorAll("p.pid");
for(var i=0; i<oP.length; i++){
document.writeln("Element P ID:"+oP[i].id);
oP[i].style.border = "medium double red";
oP[i].style.padding = "10px";
}
document.write("</pre>");
</script>
使用Document对象,获取当前文档的信息:
<script>
document.writeln("<pre>");
document.writeln("characterSet:"+document.characterSet);
document.writeln("charset:"+document.charset);
document.writeln("compatMode:"+document.compatMode);
document.writeln("defaultCharset:"+document.defaultCharset);
document.writeln("dir:"+document.dir);
document.writeln("domain:"+document.domain);
document.writeln("lastModified:"+document.lastModified);
document.writeln("referrer:"+document.referrer);
document.writeln("title:"+document.title);
document.write("</pre>");
</script>
location对象,获取文档URL信息:
<script>
document.writeln("<pre>");
document.writeln(document.location.protocol);
document.writeln(document.location.host);
document.writeln(document.location.hostname);
document.writeln(document.location.port);
document.writeln(document.location.pathname);
document.writeln(document.location.search);
document.writeln(document.location.hash);
document.write("</pre>");
</script>
location导航:
<button id="btn">Press Me</button>
<p>Actually, there are some codes hiding in the word I think.</p>
<img src="images/banana.png" alt="ban" width="200" id="banana">
<script>
document.getElementById("btn").onclick = function(){
document.location.hash = "banana";
}
</script>
assign方法:
<button id="pressme">Press Me</button>
<script>
var btn = document.getElementById("pressme");
btn.onclick = function(){
// document.location.assign("http://www.mi.com");
document.location.replace("http://www.mi.com");
}
</script>
使用 cookie :
<p id="readcookie"></p>
<button id="create">Create Cookie</button>
<button id="update">Update Cookie</button>
<script>
var content = document.getElementById("readcookie");
var create = document.getElementById("create");
var update = document.getElementById("update");
var cookieCount = 0;
create.onclick = function(){
cookieCount++;
// document.cookie = "Cookie_"+cookieCount+"=Value_"+cookieCount;
document.cookie = "name=value";
readCookie();
}
update.onclick = function(){
document.cookie = "Cookie_"+cookieCount+"=Updated_"+cookieCount;
readCookie();
}
readCookie();
function readCookie(){
content.innerHTML = document.cookie;
}
</script>
document的就绪状态:
<button id="presssate">press me</button>
<pre id="state"></pre>
<script>
document.onreadystatechange = function(){
if(document.readyState == "interactive"){
document.getElementById("presssate").onclick = function(){
document.getElementById("state").innerHTML = "Button Pressed";
}
}
}
</script>
获取浏览器的DOM实现情况:
<script>
var features = ["Core", "HTML", "CSS", "Selectors-API"];
var levels = ["1.0", "2.0", "3.0"];
document.writeln("<pre>");
for(var i=0; i<features.length; i++){
document.writeln("Checking for feature: "+features[i]);
for(var j=0; j<levels.length; j++){
document.writeln(features[i]+" Level "+levels[j]+": ");
document.writeln(document.implementation.hasFeature(features[i],levels[j]));
}
}
document.write("</pre");
</script>
使用Document对象的系列属性,来获取文档中的元素对象:
<img src="images/lemon.png" alt="lemon" id="lemon" width="150">
<p>Frankness is a basis to each member in the family.</p>
<img src="images/apple.png" alt="apple" id="apple" width="150">
<p>Frankness is a basis to each member in the family.</p>
<img src="images/banana.png" alt="banana" id="banana" width="150"><br>
<pre id="des"></pre>
<script>
var result = document.getElementById("des");
var oImg = document.images;
for(var i=0;i<oImg.length;i++){
result.innerHTML += "Image Element: "+oImg[i].id + "\n";
}
var aImg = oImg.namedItem("apple");
result.innerHTML += "Src for apple element is: "+aImg.src + "\n";
</script>
使用数组标记,来获取已命名元素:
<img src="images/lemon.png" alt="lemon" id="lemon1" width="150" name="image">
<p>Frankness is a basis to each member in the family.</p>
<img src="images/apple.png" alt="apple" id="apple1" width="150" name="image">
<p>Frankness is a basis to each member in the family.</p>
<img src="images/banana.png" alt="banana" id="banana1" width="150"><br>
<pre id="desc"></pre>
<script>
var desc = document.getElementById("desc");
// var ele = document["image"];
var ele = document.apple1;
if(ele.namedItem){
for(var i=0;i<ele.length;i++){
desc.innerHTML += "Images Element: "+ele[i].id + "\n";
}
}else{
desc.innerHTML += "Src for element is: "+ele.src + "\n";
}
</script>
使用Document对象的相关方法,来获取元素:
<pre id="selec"></pre>
<script>
var selec = document.getElementById("selec");
var oPPP = document.getElementsByTagName("p");
var oImgs = document.getElementsByName("image");
var oC = document.getElementsByClassName("little");
selec.innerHTML += oPPP.length + "\n";
selec.innerHTML += oImgs.length +"\n";
selec.innerHTML += oC.length + "\n";
</script>
使用CSS选择器来匹配文档中的元素对象:
<script>
var objs = document.querySelectorAll("p, img#apple, pre,a");
document.writeln("CSS选择器,选中了 "+objs.length +" 个元素");
</script>
链式搜索元素对象:
<p id="tb">
Never pursue literature as a trade.
<span id="sp1">apple</span>
Never pursue literature as a trade.
<span id="sp2">banana</span>
Never pursue literature as a trade.
<span id="sp3">lemon</span>
Never pursue literature as a trade.
</p>
<pre id="haha"></pre>
<script>
var oPre = document.getElementById("haha");
var oSpan1 = document.getElementById("tb").getElementsByTagName("span");
var oSpan2 = document.getElementById("tb").querySelectorAll("span");
var oSpan3 = document.querySelectorAll("#tb>span");
oPre.innerHTML += oSpan1.length + "\n";
oPre.innerHTML += oSpan2.length + "\n";
oPre.innerHTML += oSpan3.length + "\n";
</script>
在DOM树中导航,选取元素:
<div>
<p>Never pursue literature as a trade.</p>
<a href="#">apple</a>
<p>Never pursue literature as a trade.</p>
<div>
<p>Never pursue literature as a trade.</p>
<span>apple</span>
</div>
<p>Never pursue literature as a trade.</p>
<span>apple</span>
</div>
<pre id="opre"></pre><br>
<div class="btns">
<button id="parent">Parent</button>
<button id="child">First Child</button>
<button id="prev">Prev Sibling</button>
<button id="next">Next Sibling</button>
</div>
<script>
var oPr = document.getElementById("opre");
var elems = document.body;
var oBtns = document.querySelectorAll(".btns button");
for(var i=0; i<oBtns.length; i++){
oBtns[i].onclick = handleBtnClick;
}
function handleBtnClick(e){
oPr.innerHTML = "";
if(elems.style){
elems.style.backgroundColor = "white";
}
if(e.target.id == "parent" && elems != document.body){
elems = elems.parent;
}else if (e.target.id=="child" && elems.hasChildNodes()) {
elems = elems.firstChild;
}else if (e.target.id=="prev" && elems.previousSibling()) {
elems = elems.previousSibling;
}else if (e.target.id=="next" && elems.nextSibling()) {
elems = elems.nextSibling;
}
processNewElement(elems);
if(elems.style){
elems.style.backgroudColor = "lightgray";
}
function processNewElement(){
oPr.innerHTML += "元素类型:"+elems + "\n";
oPr.innerHTML += "id值:"+elems.id + "\n";
oPr.innerHTML += "是否有子元素:"+elems.hasChildNodes() +"\n";
if(elems.previousSibling){
oPr.innerHTML += "前一个兄弟元素是:"+elems.previousSibling+"\n";
}else{
oPr.innerHTML += "没有上一个兄弟元素";
}
if(elems.nextSibling){
oPr.innerHTML += "下一个兄弟元素是:"+elems.nextSibling+"\n";
}else {
oPr.innerHTML += "没有下一个兄弟元素";
}
}
}
</script>
二十七、Window对象
两种方式,获取window对象
<table id="win" border="1">
<tr>
<th>OuterWidht:</th>
<td id="owidth"></td>
</tr>
<tr>
<th>OuterHeight:</th>
<td id="oheight"></td>
</tr>
</table>
<script>
var oW = document.getElementById("owidth"),
oH = document.getElementById("oheight");
oW.innerHTML = window.outerWidth;
oH.innerHTML = document.defaultView.outerHeight;
</script>
获取窗口相关信息
<table id="win2" border="1">
<tr>
<th>outerWidth:</th>
<td id="ow"></td>
<th>outerHeight:</th>
<td id="oh"></td>
</tr>
<tr>
<th>innerWidth:</th>
<td id="iw"></td>
<th>innerHeight:</th>
<td id="ih"></td>
</tr>
<tr>
<th>screen.width</th>
<td id="sw"></td>
<th>screen.height</th>
<td id="sh"></td>
</tr>
</table>
<script>
document.getElementById("ow").innerHTML = window.outerWidth;
document.getElementById("oh").innerHTML = window.outerHeight;
document.getElementById("iw").innerHTML = window.innerWidth;
document.getElementById("ih").innerHTML = window.innerHeight;
document.getElementById("sw").innerHTML = window.screen.width;
document.getElementById("sh").innerHTML = window.screen.height;
</script>
与窗口进行交互:
<div class="axure">
<button id="scroll">scroll</button>
<button id="print">print</button>
<button id="close">close</button>
</div>
<p style="width: 800px;margin: 20px;">
First, I want to tell you how proud we are.
</p>
<script>
var buttons = document.querySelectorAll(".axure button");
for(var i=0; i<buttons.length; i++){
buttons[i].onclick = function(e){
switch (this.id) {
case "scroll":
window.scrollBy(0,3200);
break;
case "print":
window.print();
break;
case "close":
window.close();
break;
}
}
}
</script>
四种弹框:
<div id="box">
<button id="alert">alert</button>
<button id="confirm">confirm</button>
<button id="prompt">prompt</button>
<button id="modal">Show Modal Dialog</button>
</div>
<script>
var oBox = document.querySelectorAll("#box button");
for(var i=0; i<oBox.length; i++){
oBox[i].onclick = handleClick;
}
function handleClick(e){
switch (this.id) {
case "alert":
window.alert("这是警告框!");
break;
case "confirm":
var con = window.confirm("您确认要下载该软件吗?");
alert("用户是否选择的确认? " +con);
break;
case "prompt":
var str = window.prompt("请输入你名字:")
alert("用户输入的字符串是: "+str);
break;
case "modal":
window.showModalDialog("http://www.mi.com");
break;
}
}
</script>
history操作:
<div id="his">
<button id="back">Back</button>
<button id="forw">Forward</button>
<button id="go">Go</button>
</div>
<script>
var bts = document.querySelectorAll("#his button");
for(var i=0;i<bts.length;i++){
bts[i].onclick = handleHis;
}
function handleHis(){
switch (this.id) {
case "back":
window.history.back();
break;
case "forw":
window.history.forward();
break;
case "go":
window.history.go(3);
break;
}
}
</script>
innerHTML
<p id="msg"></p>
<button id="ban" class="btns">Banana</button>
<button id="app" class="btns">Apple</button>
<script>
var sel = "No selection made."
var oPPP = document.getElementById("msg");
oPPP.innerHTML = sel;
var oBBB = document.querySelectorAll(".btns");
for(var i=0; i<oBBB.length; i++){
oBBB[i].onclick = function(){
oPPP.innerHTML = this.innerHTML;
}
}
</script>
在浏览器历史中,插入条目:
<div id="insert">
<p id="msg"></p>
<button id="apple">Apple</button>
<button id="banana">Banana</button>
</div>
<script>
var sel = "No selection made.";
var oomsg = document.querySelectorAll("#insert #msg");
if(window.location.search == "?banana"){
sel = "Selection: Banana";
}else if (window.location.search == "?apple") {
sel = "Selction: Apple";
}
oomsg[0].innerHTML = sel;
var oobt = document.querySelectorAll("#insert button");
for(var i=0; i<oobt.length; i++){
oobt[i].onclick = function(e){
oomsg[0].innerHTML =e.target.innerHTML;
window.history.pushState("","","?"+this.id);
window.history.pushState("","","otherpage.html?"+this.id);
}
}
</script>
在浏览器历史中保存更为复杂的数据:
<table id="data" border="1">
<tr>
<th>Name:</th>
<td id="name"></td>
</tr>
<tr>
<th>Color:</th>
<td id="color"></td>
</tr>
<tr>
<th>Size:</th>
<td id="size"></td>
</tr>
<tr>
<th>State:</th>
<td id="state"></td>
</tr>
<tr>
<th>Event:</th>
<td id="event"></td>
</tr>
</table>
<button id="ba" class="bt">Banana</button>
<button id="ap" class="bt">Apple</button>
<script>
if(window.history.state){
displayState(window.history.state);
document.getElementById("state").innerHTML = "Yes";
}else{
document.getElementById("name").innerHTML = "No Selection";
}
window.onpopstate = function(e){
displayState(e.state);
document.getElementById("event").innerHTML = "Yes";
}
var bb = document.querySelectorAll(".bt");
for(var i=0;i<bb.length;i++){
bb[i].onclick = function(e){
var stateObj;
if(e.target.id == "ba"){
stateObj = {
name:"banana",
color:"yellow",
size:"large"
}
}else {
stateObj = {
name:"apple",
color:"red",
size:"medium"
}
}
window.history.pushState(stateObj,"");
displayState(stateObj);
};
}
function displayState(obj){
document.getElementById("name").innerHTML = obj.name;
document.getElementById("color").innerHTML = obj.color;
document.getElementById("size").innerHTML = obj.size;
}
</script>
替换浏览器历史条目
<div id="rep">
<p id="ms"></p>
<button id="baa">Banana</button>
<button id="apl">Apple</button>
</div>
<script>
var sel = "no selection."
if(window.location.search == "Banana"){
sel = "Sel: Banana";
}else if (window.location.search == "Apple") {
sel = "Sel: Apple";
}
document.getElementById("ms").innerHTML = sel;
var bs = document.querySelectorAll("#rep button");
for(var i=0; i<bs.length;i++){
bs[i].onclick = function(e){
document.getElementById("ms").innerHTML = this.innerHTML;
window.history.replaceState("","","?"+this.id);
}
}
</script>
跨文档消息传递:
<script>
window.addEventListener("message", handleMessage, false);
function handleMessage(e){
if(e.origin == "http://titan"){
displayMessage(e.data);
}else {
displayMessage("No Message");
}
}
function displayMessage(msg){
document.getElementById("banana").innerHTML = msg;
}
</script>
计时器:
<div id="time">
<p id="timemsg"></p>
<button id="settime">SetTime</button>
<button id="setinterval">SetInterval</button>
<button id="cleartime">ClearTime</button>
<button id="clearinterval">ClearInterval</button>
</div>
<script>
var tts = document.querySelectorAll("#time button");
for(var i=0; i<tts.length; i++){
tts[i].onclick = handleTime;
}
var timeId;
var intervalId;
var count = 0;
function handleTime(e){
if(e.target.id == "settime"){
timeId = window.setTimeout(function(){
disMsg("Timeout Expired.");
},3000);
disMsg("time out");
}else if (e.target.id == "cleartime") {
window.clearTimeout(timeId);
disMsg("time out cleared.");
}else if (e.target.id == "setinterval") {
intervalId = window.setInterval(function(){
disMsg("Interval expired. Counter: "+count++);
},1000);
disMsg("interval");
}else if (e.target.id == "clearinterval") {
window.clearInterval(intervalId);
disMsg("interval cleared");
}
}
function disMsg(msg){
document.getElementById("timemsg").innerHTML = msg;
}
</script>
二十八、DOM元素
使用HTMLElement对象的一些属性:
<p id="textblock" dir="ltr" lang="en-US">
这是一个段落!!!
<span id="banana">banana.</span>这是一个段落!!!
<span id="apple">apple.</span>这是一个段落!!!
<span id="orange">orange.</span>
这是一个段落!!!
</p>
<pre id="res"></pre>
<script>
var res = document.getElementById("res");
var oP = document.getElementById("textblock");
res.innerHTML += "tag: "+oP.tagName +"<br>";
res.innerHTML += "id: "+oP.id +"<br>";
res.innerHTML += "dir: "+oP.dir +"<br>";
res.innerHTML += "lang: "+oP.lang +"<br>";
res.innerHTML += "hidden: "+oP.hidden +"<br>";
res.innerHTML += "disabled: "+oP.disabled +"<br>";
</script>
使用className属性:
<style>
#p {
border: medium solid red;
}
.newClass {
background-color: grey;
color: white;
}
.haha {
font-size: 20px;
font-weight: bold;
padding: 10px;
}
</style>
<button id="addClass">Add Class</button>
<script>
var addClass = document.getElementById("addClass");
addClass.onclick = function(){
oP.className += " newClass";
}
</script>
使用classList属性:
<pre id="classList"></pre><br>
<button id="toggle">Toggle</button>
<button id="add">Add Class</button>
<script>
var oList = document.getElementById("classList");
document.getElementById("toggle").onclick = toggleClass;
document.getElementById("add").onclick = add;
disClass();
function toggleClass(){
oP.classList.toggle("newClass");
disClass();
}
function disClass(){
oList.innerHTML = "Current class: ";
var list = oP.classList;
for(var i=0;i<list.length;i++){
oList.innerHTML += list[i]+" ";
}
}
function add(){
oP.classList.add("haha");
disClass();
}
</script>
DOM对象的属性操作:
<p id="attrDo">这又是一个段落!</p>
<pre id="msgDo"></pre>
<script>
var msg = document.getElementById("msgDo");
var op1 = document.getElementById("attrDo");
msg.innerHTML = "元素是否有lang属性: "+op1.hasAttribute("lang")+"<br>";
msg.innerHTML += "为元素添加lang属性: "+"<br>";
op1.setAttribute("lang","en-US");
msg.innerHTML += "元素的lang属性值是: "+op1.getAttribute("lang") + "<br>";
</script>
操作元素的自定义属性:
<p id="datas" data-app="haha" data-web="hehe" data-and="kuku">自定义属性</p>
<script>
var od = document.getElementById("datas");
console.log(od.dataset);
for(var attr in od.dataset){
document.writeln(attr+": "+od.dataset[attr]+"<br>");
}
</script>
<script>
od.attributes["app"] = "apple";
for(var attr in od.attributes){
document.writeln(attr+": "+od.attributes[attr]+"<br />");
}
console.log(od.attributes)
</script>
文本对象:
<p id="text">文本对象</p>
<button id="replace">Replace</button>
<script>
var oText = document.getElementById("text");
console.log(oText.firstChild.length);
document.getElementById("replace").onclick = function(){
oText.firstChild.data = "没了";
}
</script>
DOM创建和删除元素:
<table border="1">
<thead>
<th>Name</th>
<th>Color</th>
</thead>
<tbody id="fruit">
<tr>
<td>banana</td>
<td>yellow</td>
</tr>
<tr>
<td>apple</td>
<td>red</td>
</tr>
</tbody>
</table>
<button id="addFruit">Add</button>
<button id="removeFruit">Remove</button>
<style>
table{border: solid thin red;border-collapse: collapse;margin: 10px;}
td {padding: 4px 5px;}
</style>
<script>
document.getElementById("addFruit").onclick = function(){
var row = document.createElement("tr");
row.className = "row";
row.appendChild(document.createElement("td")).appendChild(document.createTextNode("Plum"));
row.appendChild(document.createElement("td")).appendChild(document.createTextNode("purple"));
document.getElementById("fruit").appendChild(row);
}
document.getElementById("removeFruit").onclick = function(){
var childs = document.querySelectorAll(".row");
for(var i=0; i<childs.length; i++){
childs[i].parentNode.removeChild(childs[i]);
}
}
</script>
克隆节点:
<button id="clone">clone</button>
<table border="1">
<thead>
<th>乘</th>
<th>结果</th>
</thead>
<tbody id="cheng">
<tr>
<td>1*2</td>
<td>2</td>
</tr>
</tbody>
</table>
<script>
var count = 3;
document.getElementById("clone").onclick = function(){
var newEl = document.getElementById("cheng").children[0].cloneNode(true);
newEl.children[0].firstChild.data=count+1+"*"+count;
newEl.children[1].firstChild.data=(count+1)*count;
document.getElementById("cheng").appendChild(newEl);
count++;
}
</script>
移动元素:
<button id="move">Move</button>
<table border="1" id="dos">
<tr>
<td>名字</td>
<td>颜色</td>
</tr>
<tr id="app">
<td>apple</td>
<td>red</td>
</tr>
<tr id="ban">
<td>banana</td>
<td>yellow</td>
</tr>
</table>
<table id="do" border="1">
<tr>
<td>名字</td>
<td>颜色</td>
</tr>
<tr>
<td>plum</td>
<td>purple</td>
</tr>
</table>
<style>
td,th{width: 50px; text-align: center;}
</style>
<script>
var flag=true;
document.getElementById("move").onclick = function(){
if(flag){
document.getElementById("do").appendChild(document.getElementById("app"));
document.getElementById("do").appendChild(document.getElementById("ban"));
flag = false;
}else {
document.getElementById("dos").appendChild(document.getElementById("app"));
document.getElementById("dos").appendChild(document.getElementById("ban"));
flag = true;
}
}
</script>
对象的比较:
<div id="box">
<p>00329212</p>
<p id="pid">iooweiow</p>
<p>00929id0</p>
<p class="hehe" title="11">1204204</p>
<p class="hehe" title="11">1204204</p>
</div>
<pre id="ms"></pre>
<pre id="mss"></pre>
<script>
var oP1 = document.getElementById("pid");
var oP2 = document.getElementById("box").children[1];
if(oP1.isSameNode(oP2)){
document.getElementById("ms").innerHTML = "这两个元素是相同的!";
}else {
document.getElementById("ms").innerHTML = "这两个元素不相同!";
}
</script>
<script>
var oPs = document.querySelectorAll("p.hehe");
if(oPs[0].isEqualNode(oPs[1])){
document.getElementById("mss").innerHTML += "它们相等!"+"<br />";
}else {
document.getElementById("mss").innerHTML += "它们不相等!"+"<br />";
}
if(oPs[0].isSameNode(oPs[1])){
document.getElementById("mss").innerHTML += "它们是同一对象"+"<br />";
}else {
document.getElementById("mss").innerHTML += "它们是不同的对象"+"<br />";
}
</script>
innerHTML / outerHTML
<div id="box2">
<ul id="uls">
<li>oiwoei</li>
<li>oiw<span>ioweo</span>oei</li>
<li>oiwoei</li>
<li id="lis">oi<span>ioweo</span>woei</li>
<li>oiwoei</li>
</ul>
</div>
<button id="in">inner</button>
<button id="out">outer</button><br>
<textarea name="text1" id="text1" cols="100" rows="10"></textarea>
<script>
var uls = document.getElementById("uls");
document.getElementById("in").onclick = function(){
document.getElementById("text1").innerHTML = uls.innerHTML;
}
document.getElementById("out").onclick = function(){
document.getElementById("text1").innerHTML = uls.outerHTML;
}
</script>
<div id="uls2">
<ul>
<li id="bb">列表列表</li>
<li>列表列表</li>
<li>列表列表</li>
<li id="aa">列表列表</li>
</ul>
</div>
<button id="move11">Move</button>
<script>
var lis = document.getElementById("lis");
var tar = document.getElementById("uls2").children[0].children[3];
document.getElementById("move11").onclick = function(){
tar.innerHTML = lis.innerHTML;
document.getElementById("uls2").children[0].children[0].outerHTML = "<p><a href='http://www.baidu.com'"
+"target='_blank'>百度</a></p>";
}
</script>
insertAdjacentHTML:
<div id="insert">
<button>最前面</button>
<button>第一个子元素</button>
<button>最后一个子元素</button>
<button>最后面</button>
</div>
<div id="tabs" style="background-color: gray;">
<p>子元素</p>
</div>
<script>
var bbs = document.querySelectorAll("#insert button");
var target = document.getElementById("tabs").children[0];
for(var i=0; i<bbs.length; i++){
bbs[i].index = i+1;
bbs[i].onclick = function(){
switch (this.index) {
case 1:
target.insertAdjacentHTML("beforebegin","<td>在前面</td>");
break;
case 2:
target.insertAdjacentHTML("afterbegin","<td>第一个子元素</td>");
break;
case 3:
target.insertAdjacentHTML("beforeend","<td>最后一个子元素</td>");
break;
case 4:
target.insertAdjacentHTML("afterend","<td>在后面</td>");
break;
}
}
}
</script>
向文本块插入元素节点:
<p id="text2">Stay Foolish. Stay Hungry.</p>
<button id="inser">insert element</button>
<style>
b {color: red;}
</style>
<script>
document.getElementById("inser").onclick = function(){
var textNode = document.getElementById("text2");
var newText1 = textNode.firstChild.splitText(6);
var newText2 = textNode.childNodes[1].splitText(4).previousSibling;
textNode.insertBefore(document.createElement("b"),newText2).appendChild(newText2);
}
</script>
二十九、为DOM元素设置样式
<head>
<style>
p{
border: 1px solid red;
background-color: lightgray;
}
#block1 {color: white;}
table {
border: thin solid blue;
border-collapse: collapse;
margin: 5px;float: left;
}
td {
padding: 5px;
}
</style>
<style media="screen AND (min-width:500px), PRINT" type="text/css">
#block2 {
color: yellow;
font-style: italic;
}
</style>
<link rel="stylesheet" href="#">
</head>
获得样式表的基本信息:
<p id="block1">Stay Foolish.</p>
<p id="block2">Stay Hungry.</p>
<button id="getStyle">获取样式表的信息</button>
<div id="place"></div>
<script>
var sheets = document.styleSheets;
console.log(sheets);
var box = document.getElementById("place");
document.getElementById("getStyle").onclick = function(){
for(var i=0; i<sheets.length; i++){
var table = document.createElement("table");
table.border = "1";
addRow(table,"Index",i);
addRow(table,"href",sheets[i].href);
addRow(table,"title",sheets[i].title);
addRow(table,"type",sheets[i].type);
addRow(table,"ownerNode",sheets[i].ownerNode.tagName);
box.appendChild(table);
};
};
function addRow(obj,cont1,cont2){
var row = document.createElement("tr");
row.innerHTML = "<td>"+cont1+"</td><td>"+cont2+"</td>";
obj.appendChild(row);
}
</script>
使用MediaList对象:
<button id="getMedia">获取MediaList对象相关信息</button>
<div id="place2"></div>
<script>
var box2 = document.getElementById("place2");
var shs = document.styleSheets;
document.getElementById("getMedia").onclick = function(){
for(var i=0; i<shs.length;i++){
if(shs[i].media.length > 0){
var tab = document.createElement("table");
tab.border = "1";
addRow(tab,"媒体的数量",shs[i].media.length);
addRow(tab,"媒体文本值",shs[i].media.mediaText);
for(var j=0; j<shs[i].media.length; j++){
addRow(tab,"第"+j+"条媒体",shs[i].media.item[0]);
}
box2.appendChild(tab);
}
}
};
</script>
禁用或启用样式表:
<button id="toggle">禁用或启用样式表</button>
<script>
var shss = document.styleSheets;
document.getElementById("toggle").onclick = function(){
for(var i=0; i<shss.length; i++){
shss[i].disabled = !shss[i].disabled;
}
}
</script>
进一步使用样式表对象:
<button id="sh1">操作CSSRuleList对象</button>
<button id="sh2">使用CSSRuleList对象修改样式表中的样式规则</button>
<div id="place3"></div>
<script>
var box3 = document.getElementById("place3");
document.getElementById("sh2").onclick = function(){
document.styleSheets[0].cssRules.item(1).selectorText = "#block2";
if(box3.hasChildNodes()){
for(var i=0; i<box3.childNodes.length; i++){
box3.removeChild(box3.childNodes.firstChild);
}
}
}
document.getElementById("sh1").onclick = processStyleSheet;
function processStyleSheet(){
var rules = document.styleSheets[0].cssRules;
for(var i=0; i<rules.length; i++){
var rule = rules.item(i);
var ta = document.createElement("table");
ta.border = "1";
addRow(ta,"父级样式表",rule.parentStyleSheet.title);
addRow(ta,"选择器字符串",rule.selectorText);
addRow(ta,"样式内容",rule.cssText);
box3.appendChild(ta);
}
}
</script>
操作元素的行内样式:
<button id="doStyle">更改行内样式</button>
<button id="doStyle1">展示行内样式</button>
<div id="msg"></div>
<script>
var msg = document.getElementById("msg");
var target = document.getElementById("block1");
document.getElementById("doStyle").onclick = function(){
target.style.cssText = "font-size:26px; color:red;";
disStyle();
}
document.getElementById("doStyle1").onclick = disStyle;
function disStyle(){
if(msg.hasChildNodes()){
for(var i=0; i<msg.childNodes.length; i++){
msg.removeChild(msg.firstChild);
}
}
var text = document.getElementById("block1").style.cssText;
msg.innerHTML = text;
}
</script>
使用 CSSStyleDeclaration对象:
<div id="dec1" class="od">Stay Foolish.</div><br>
<div id="dec2" class="od" style="border:medium dashed red;color: blue;padding: 2px;">Stay Hungry.</div><br>
<button id="btn">CSSStyleDeclaration操作</button><br>
<div id="dec"></div>
<style title="core styles" id="sty">
#dec1 {
color: white;border: thick solid blue;background-color: gray;
}
div.od {
border: thin solid black; background-color: lightgray;
}
table.taa {
border: thin solid red; border-collapse: collapse;
margin: 5px; float: left;
}
table.taa td {
padding: 5px;
}
</style>
<script>
var box4 = document.getElementById("dec");
// 点击事件,更改样式表中的样式对象
document.getElementById("btn").onclick = function(){
// document.getElementById("sty").cssRules.item(1).style.paddingTop = "10px";
// document.getElementById("sty").cssRules.item(1).style.paddingRight = "10px";
var obj1 = document.getElementById("dec2").style;
var obj2 = document.getElementById("dec1").style;
// obj.cssText = "border:1px solid red; color:blue; padding:5px; paddingTop:10px;"
displayStyle(obj1);
displayStyle(obj2);
}
function displayStyle(style2){
if(box4.hasChildNodes() && box4.childNodes.length >=2){
return false;
}
var tass = document.createElement("table");
tass.className = "taa";
tass.border = "1";
addRow(tass,"border",style2.border);
addRow(tass,"color",style2.color);
addRow(tass,"padding",style2.padding);
addRow(tass,"paddingTop",style2.paddingTop);
box4.appendChild(tass);
}
</script>
<button id="addSty">为元素添加样式</button>
<div id="msg2"></div>
<script>
var oD1 = document.getElementById("dec1");
var sty = oD1.style;
var box5 = document.getElementById("msg2");
document.getElementById("addSty").onclick = function(){
sty.setProperty("font-size","40px");
sty.setProperty("line-height","3em");
sty.setProperty("padding","20px");
disPro();
}
function disPro(){
var tb = document.createElement("table");
tb.border = "1";
addRow(tb,"字号",sty.getPropertyValue("font-size"));
addRow(tb,"行高",sty.getPropertyValue("line-height"));
addRow(tb,"内边距",sty.getPropertyValue("padding"));
box5.appendChild(tb);
}
</script>
以程序的方式探索CSS属性:
<p id="pp" style="color: red;font-size: 40px; border: 1px solid blue;">Stay Foolish.</p>
<button id="cod">显示元素样式</button>
<div id="msg3"></div>
<script>
var box6 = document.getElementById("msg3");
var sty6 = document.getElementById("pp").style;
document.getElementById("cod").onclick = function(){
box6.innerHTML = sty6.cssText;
}
</script>
获取元素样式的优先级:
<style>
#PP {
padding: 30px !important;
width: 800px;
line-height: 3em;
}
</style>
<script>
var sty7 = document.getElementById("pp").style;
var res = sty7.getPropertyPriority("padding");
document.writeln(res)
</script>
获取更加细粒度的CSS属性值:
<div id="box10" style="width: 500px; height: 200px; background-color: red; color: white; font-size: 3em; text-align: center;line-height: 200px;">盒子</div><br>
<button id="btn10">获取细粒度的单位值</button><br><br>
<div id="msg10"></div>
<script>
var sty10 = document.getElementById("box10").style;
var len = sty10.length;
var msg10 = document.getElementById("msg10");
var arr = ["width","height","background-color","color","font-size","text-align","line-height"];
document.getElementById("btn10").onclick = function(){
var table10 = document.createElement("table");
table10.border = "1";
for(var i=0; i<len; i++){
addRow(table10,arr[i],sty10.getPropertyValue(arr[i]));
}
msg10.appendChild(table10);
}
</script>
计算样式:
<script>
var obj1 = document.getElementById("box10");
var list = document.defaultView.getComputedStyle(obj1);
document.writeln(list.length+"<br />");
document.writeln(list.getPropertyValue("margin-top")+"<br />");
document.writeln(list.getPropertyValue("color")+"<br />");
document.writeln(list.getPropertyValue("height"));
console.log(document.defaultView.getComputedStyle(document.body).getPropertyValue("width"));
</script>
三十、DOM事件
内联事件处理:
<p
onmouseover="this.style.background='gray'; this.style.color='white';"
onmouseout="this.style.removeProperty('background');
this.style.removeProperty('color');">
Stay Foolish.
</p>
事件处理函数:
<p onmouseover="handleOver(this)" onmouseout="handleOut(this)">Stay Hungry.</p>
<script>
function handleOver(obj){
obj.style.backgroundColor = "gray";
obj.style.color = "red";
}
function handleOut(obj){
obj.style.removeProperty("background-color");
obj.style.removeProperty("color");
}
</script>
<p class="pe">Keep Learning.</p>
<p class="pe">Keep Happy.</p>
<script>
var pe = document.querySelectorAll(".pe");
for(var i=0; i<pe.length; i++){
pe[i].onmouseover = handleOver1;
pe[i].onmouseout = handleOut1;
}
function handleOver1(e){
e.target.style.backgroundColor="gray";
e.target.style.color = "white";
}
function handleOut1(e){
e.target.style.removeProperty("background-color");
e.target.style.removeProperty("color");
}
</script>
addEventListener()
<p class="pp">Try yourself.</p>
<p class="pp">Dare to Try.</p>
<button id="add">添加事件</button>
<button id="del">移除事件</button>
<script>
var pp = document.querySelectorAll(".pp");
document.getElementById("add").onclick = function(){
for(var i=0; i<pp.length; i++){
pp[i].addEventListener("mouseover",handleOver1);
pp[i].addEventListener("mouseout",handleOut1);
}
};
document.getElementById("del").onclick = function(){
pp[1].removeEventListener("mouseover", handleOver1);
}
</script>
使用Event对象的type属性,实现一个函数来处理多个类型的事件:
<p id="pid">Be yourself.</p>
<script>
var pid = document.getElementById("pid");
pid.addEventListener("mouseover",handle);
pid.addEventListener("mouseout",handle);
function handle(e){
switch (e.type) {
case "mouseover":
e.target.style.backgroundColor = "gray";
e.target.style.color = "red";
break;
case "mouseout":
e.target.style.removeProperty("background-color");
e.target.style.removeProperty("color");
break;
}
}
</script>
事件捕获:
<p id="block2">Be yourself.<span id="sp">Be Happy.</span></p>
<script>
var oPP = document.getElementById("block2");
var oSP = document.getElementById("sp");
oPP.addEventListener("mouseover",handlePP,true);
oPP.addEventListener("mouseout",handlePP,true);
oSP.addEventListener("mouseover",handleSP);
oSP.addEventListener("mouseout",handleSP);
function handlePP(e){
if(e.type == "mouseover" && e.eventPhase == Event.CAPTURING_PHASE){
e.target.style.border = "thin solid red";
e.currentTarget.backgroundColor = "gray";
}else if (e.type == "mouseout" && e.eventPhase == Event.CAPTURING_PHASE) {
e.target.style.removeProperty("border");
e.currentTarget.style.removeProperty("background-color");
}
e.stopPropagation();
}
function handleSP(e){
if(e.type == "mouseover"){
e.target.style.backgroundColor = "white";
e.target.style.color = "red";
}else {
e.target.style.removeProperty("background-color");
e.target.style.removeProperty("color");
}
}
</script>
<div id="haha">addEventListener</div>
<script>
var haha = document.getElementById("haha");
// haha.addEventListener("mouseover",haha1);
// haha.addEventListener("mouseover",haha2);
function haha1(e){
alert(1);
}
function haha2(e){
alert(2);
}
</script>
阻止默认事件:
<div id="stop">
<a href="http://www.mi.com">小米</a>
<a href="http://www.mi.com">小米</a>
</div>
<script>
var oA = document.querySelectorAll("#stop a");
for(var i=0; i<oA.length; i++){
oA[i].addEventListener("click",clickA);
}
function clickA(e){
var e = e | window.event;
var flag = confirm("您是否要阻止a的跳转行为?");
if(flag){
e.stopPropagation();
}
alert("我是自定义事件");
}
</script>
鼠标事件:
<style>
td,th {
width: 150px;
}
</style>
<p id="block3">Do yourself.</p>
<table border="1">
<tr>
<th>事件类型</th>
<td id="etype"></td>
</tr>
<tr>
<th>X坐标</th>
<td id="ex"></td>
</tr>
<tr>
<th>Y坐标</th>
<td id="ey"></td>
</tr>
</table>
<script>
var block3 = document.getElementById("block3");
var etype = document.getElementById("etype"),
ex = document.getElementById("ex"),
ey = document.getElementById("ey");
block3.addEventListener("mouseover",handle5);
block3.addEventListener("mousemove",handle5);
block3.addEventListener("mouseout",handle5);
function handle5(e){
switch (e.type) {
case "mouseover":
block3.style.color = "red";
break;
case "mousemove":
block3.style.fontSize = "20px";
break;
case "mouseout":
block3.removeProperty("color");
block3.removeProperty("font-size");
etype.innerHTML = "";
ex.innerHTML = "";
ey.innerHTML = "";
break;
}
if(e.eventPhase == Event.AT_TARGET){
etype.innerHTML = e.type+"";
ex.innerHTML = e.clientX;
ey.innerHTML = e.clientY;
}
}
</script>
焦点事件:
<form action="" class="form1">
<p><label for="">Fruit:<input type="text" autofocus name="fave"></label></p>
<p><label for="">Name:<input type="text" autofocus name="name"></label></p>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
<script>
var oInput = document.querySelectorAll("form.form1 input");
for(var i=0; i<oInput.length; i++){
oInput[i].addEventListener("focus",handInput);
oInput[i].addEventListener("blur",handInput);
}
function handInput(e){
switch (e.type) {
case "focus":
e.target.style.backgroundColor = "lightgray";
e.target.style.border = "thick solid red";
break;
case "blur":
e.target.style.removeProperty("background-color");
e.target.style.removeProperty("border");
break;
}
}
</script>
键盘事件:
<form action="" class="form2">
<input type="text" name="in1" autofocus><br>
<input type="text" name="in2"><br>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
<span id="msg"></span>
<script>
var oin = document.querySelectorAll(".form2 input");
for(var i=0; i<oin.length; i++){
oin[i].addEventListener("keyup",handKey);
}
function handKey(e){
document.getElementById("msg").innerHTML +="Key Pressed: "+e.key+"<br />";
document.getElementById("msg").innerHTML += "Char: "+String.fromCharCode(e.key)+"<br />";
}
</script>
三十一、使用元素专属对象
DOM文档对象模型中还定义了一组对象用来代表文档里不同类型的HTML元素,这些元素对象可以被当做 HTMLElement 对象来使用。
1)文档和元数据对象
HTMLBaseElement / HTMLBodyElement / HTMLLinkElement / HTMLMetaElement / HTMLScriptElement / HTMLStyleElement / HTMLTitleElement / HTMLHeadElement / HTMLHtmlElement。
2)文本元素对象
HTMLAnchorElement / HTMLModElement / HTMLQuoteElement / HTMLTimeElement / HTMLBRElement / HTMLSpanElement。
3)分组元素对象
HTMLQuoteElement / HTMLLIElement / HTMLOListElement。
4)区块元素对象
HTMLDetailsElement / HTMLHeadingElement / HTMLTableColElement / HTMLTableElement / HTMLTableSectionElement / HTMLTableHeaderCellElement / HTMLTableRowElement / HTMLTableCaptionElement。
5)表单元素对象
HTMLButtonElement / HTMLDataListElement / HTMLFieldSetElement / HTMLFormElement / HTMLInputElement / HTMLLabelElement / HTMLLegendElement / HTMLOptGroupElement / HTMLOptionElement / HTMLOutputElement / HTMLSelectElement / HTMLTextAreaElement。
6)内容元素对象
HTMLAreaElement / HTMLEmbedElement / HTMLIFrameElement / HTMLImageElement / HTMLMapElement / HTMLMeterElement / HTMLObjectElement / HTMLParamElement / HTMLProgressElement。
第四部分 结束!!!
网友评论