**element.addEventListener(event, function, useCapture);**
第一个参数是事件的类型 (如 "click" 或 "mousedown").
第二个参数是事件触发后调用的函数。
第三个参数是个布尔值用于描述事件是冒泡还是捕获。该参数是可选的
第一种为按钮添加事件-
html:
<P>该实例使用addEventListener()方法在按钮中添加事件</P>
<button id="myBtn">点我</button>
JS:
document.getElementById("myBtn").addEventListener("click",function(){
alert("你好啊");
});
第二种通过引用外部函数,给按钮添加事件
/*引用外部函数 注意这块只用写函数名*/
document.getElementById("btn1").addEventListener("click",myfunction);
function myfunction(){
alert ("helloword");
}
第三种向同一个实例添加两个监听事件
var x=document.getElementById("btn2");
x.addEventListener("click",myfunction1);
x.addEventListener("click",otherfunction);
function myfunction1(){
alert("hello");
}
function otherfunction(){
alert("word");
}
向 Window 对象添加事件句柄
addEventListener() 方法允许你在 HTML DOM 对象添加事件监听,
HTML DOM 对象如:HTML 元素, HTML 文档, window 对象。
或者其他支出的事件对象如: xmlHttpRequest 对象
修改CSS样式
<script type="text/javascript">
window.onload=function(){
document.getElementById('btn1').addEventListener('click',myfunction);
function myfunction(){
var box=document.getElementById('box');
box.style.color='red';
}
}
</script>
<input type="button" id="btn1" value="变色按钮"/>
<div id="box" style="width: 100px;height: 100px;background-color: aqua;">你好啊</div>
传递参数
当传递参数值时,使用"匿名函数"调用带参数的函数:
var p1=5;
var p2=7;
document.getElementById("btn3").addEventListener("click",function(){
myfunction2(p1,p2);
})
function myfunction2(a,b){
var result=a*b;
document.getElementById("demo").innerHTML=result;//35
}
removeEventListener() 方法
removeEventListener() 方法移除由 addEventListener() 方法添加的事件句柄:
getPropertyValue由三个单词构成:
(1).get:获取。
(2).property:属性。
(3).value:值。
cssRules返回的是一个规则集合,通过索引可以获取指定位置的规则。 通过cssText属性可以获取具体的规则内容。
<style type="text/css">
div {
text-align:center;
background-color:#ccc;
font-size:12px;
}
#ant {
width:300px;
height:100px;
}
</style>
<script>
/*
* cssRules返回的是一个规则集合,通过索引可以获取指定位置的规则。
通过cssText属性可以获取具体的规则内容。
*/
window.onload = function () {
let odiv = document.getElementById("ant");
let obt = document.getElementById("bt");
let styleSheet = document.styleSheets[0];
obt.onclick = function () {
odiv.innerHTML = styleSheet.cssRules[1].cssText;
}
}
</script>
</head>
<body>
<div id="ant"></div>
<input type="button" id="bt" value="查看效果"/>
insertRule方法可以在样式表中插入新的规则
stylesheet.insertRule(rule, index)
<style type="text/css">
div {
text-align:center;
background-color:red;
}
#ant {
width:120px;
height:40px;
}
</style>
<script>
window.onload = function () {
document.getElementById('bt').addEventListener('click',myfunction)
function myfunction(){
let styleSheet = document.styleSheets[0];
styleSheet.insertRule("#ant{color:blue}");
}
}
</script>
</head>
<body>
<div id="ant">蚂蚁部落</div>
<input type="button" id="bt" value="变色"/>
deleteRule方法可以删除样式表中的指定规则。
stylesheet.deleteRule(index)
index:必需,被删除规则在样式表中的索引位置
window.onload = function () {
let odiv = document.getElementById("ant");
let obt = document.getElementById("bt");
let styleSheet = document.styleSheets[0];
obt.onclick = function () {
styleSheet.deleteRule(0);
}
}