句柄DOM监听事件
document.getElementById("btn").addEventListener("click",
function(){
alert("句柄监听事件");
}
);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div">hello</p> <button onclick="demo()">按钮1</button> <button id="btn">按钮2</button> <button id="btn_many">添加多个句柄事件</button> <script> // 以前的监听 function demo(){ document.getElementById("div").innerHTML = "改变" } // 句柄式监听 document.getElementById("btn").addEventListener("click", function(){ alert("句柄监听事件"); } ); // 声明多个句柄 var x = document.getElementById("btn_many"); x.addEventListener("click",hello); x.addEventListener("click",world); // 移出句柄 x.removeEventListener("click",hello); function hello(){ alert("hello") } function world(){ alert("world") } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .div{ height: 100px; width: 100px; background-color: brown; } </style> </head> <body> <!-- 通过dom对象改变css --> <!-- 语法:document.getElementById(id).style.property=new style --> <div id="div" class="div">通过dom改变样式</div> <p id="pid">改变html</p> <button onclick="demo()">改变颜色</button> <button onclick="demo1()">改变内容</button> <script> function demo(){ document.getElementById("div").style.background = "blue"; } function demo1(){ var nv = document.getElementById("pid").innerHTML="哈哈"; document.getElementsByTagName("p"); // 通过标签寻找 } </script> </body> </html>
------------------------
#### 通过dom对象改变css
<!-- 语法:document.getElementById(id).style.property=new style -->
-------------------------------
#### 通过dom操作html
document.write("hello");
function demo1(){
var nv = document.getElementById("pid").innerHTML="哈哈";
}
兼容不同浏览器的事件(IE8一下)
var btn1 = document.getElementById("btn1");
if(btn1.addEventListener){
btn1.addEventListener("click",demo);
}else if(btn1.attachEvent){
btn1.attachEvent("onclick",demo);
}else{
btn1.onclick = demo();
}
function demo(){
alert("hello);
}