DOM
/Dom 表示的是文檔對象模型document object model/
1:作用:JS可以通過DOM來操作網頁;
// 文檔表示的是整個網頁,元素節點表示的是標簽,屬性節點表示的元素的屬性,文本節點是標簽中的文字; varb=document.getElementById("sn");//通過ID來獲取對象 b.innerText="bojg"; <buttonid="sn">按鈕</button> <scripttype="text/javascript"> var b=document.getElementById("sn");//通過ID來獲取對象 b.innerText="bojg"; </script>
2:事件:事件是用戶與遊覽器的交互(一些行為例如)點擊,雙擊,鼠標移動,關閉窗口
我們可以在事件中對應的屬性中設置一些JS代碼當事件觸發時候運行。
事件可以查相應的文檔。
<body> <buttonondblclick="alert('別點我')">按鈕</button> //按鈕在被雙擊的時候執行代碼 </body>
3:為對應事件綁定函數來響應事件
<body> <buttonid="sm">按鈕</button> <scripttype="text/javascript"> //首先我們要獲取標簽對象; varbut=document.getElementById("sm")//通過ID屬性來獲取對象; //綁定事件 but.onclick=function(){ alert("別點我"); } </script> </body>
4:練習圖片
<!DOCTYPEhtml> <html> <head> <metacharset="UTF-8"> <title></title> <styletype="text/css"> *{ margin: 0; padding:0 ; } .box1{ width: 450px; background-color:#bfa; padding:10px ; text-align:center; margin: 50pxauto; } </style> <scripttype="text/javascript"> window.onload=function(){ varpre=document.getElementById("pre"); varnext=document.getElementById("next"); varimg=document.getElementsByTagName("img")[0]; var index=0; varimge=["img/1.jpg" , "img/2.jpg", "img/3.jpg", "img/4.jpg"]; pre.onclick=function(){ index--; if(index<0) { index=0; } img.src=imge[index]; }; next.onclick=function(){ index++; if(index>imge.length-1) { index=imge.length-1; } img.src=imge[index]; } }; </script> </head> <body> <divclass="box1"> <imgsrc="img/1.jpg"/> <p></p> <buttonid="pre">上一張</button> <buttonid="next">下一張</button> </p> </body> </html>