<!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 style="display:grid;gap:0.5em;">
<!-- 1.通过元素的属性:on +事件名称(事件属性),直接写到元素中的 缺点:将JS代码过多写入到html中,没有实现元素行为和结构的彻底分离-->
<button onclick="alert('hello')">标签属性</button>
<!-- <button onclick="hello()">提交</button> -->
<script>
function hello(){
alert("hello");
}
</script>
<!-- 2.元素对象添加属性的方式,动态添加到元素中缺点:事件方法之间相互覆盖 -->
<button>动态属性</button>
<script>
const bth2=document.querySelector("button:nth-of-type(2)");
bth2.onclick=function(){
alert(1);
};
bth2.onclick=function(){
alert(200);
};
// 事件的删除
bth2.onclick=null;
</script>
<!-- 事件监听器 -->
<button>监听器</button>
<button>点击广告</button>
<script>
// bth3.addEventListener(事件类型,事件回调/方法名,是否冒泡/false)
const bth3=document.querySelector("button:nth-of-type(3)");
bth3.addEventListener("click",function(){
alert('aaa');
});
// bth3.addEventListener("click",function(){
// alert('bbb');
// });
// 移除浏览器弹窗bbb
// 如果事件方法使用了回调,则无法移除
// bth3.removeEventListener("click",function(){
// alert("bbb");
// });
bth3.addEventListener("click",show);
function show(){
alert("bbb");
}
bth3.removeEventListener("click",show);
// 事件派发
// const myclick= new Event("click");
// const bth4 =document.querySelector("button:nth-of-type(4)");
// bth4.onclick=()=>alert(333);
// bth4.dispatchEvent(myclick);
// let i=0;
// bth4.addEventListener("click",()=>{
// console.log("点击了广告,已经赚了:" + i +"元");
// i += 0.2;
// });
const myclick= new Event("click");
const bth4 =document.querySelector("button:nth-of-type(4)");
// bth4.onclick=()=>alert(333);
// 间歇式定时器开启
let i=0;
bth4.addEventListener("click",()=>{
console.log("点击了广告,已经赚了:" + i +"元");
i += 0.2;
setInterval (()=>bth4.dispatchEvent(myclick),3000);
});
</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>
.red{
color: red;
}
.bgc{
background-color:yellow;
}
.blue {
color: blue;
}
h2{
border:5px solid red;
}
</style>
</head>
<body>
<h2 style = "font-size:50px;">hello world</h2>
</body>
<script>
// 过时了
// document.querySelector("h2").className="red bgc";
const h2 = document.querySelector("h2");
// h2.classList:动态设置元素的class
// 1.添加红色和背景色黄色
h2.classList.add("red");
h2.classList.add("bgc");
// 2.移除背景色黄色
h2.classList.remove("bgc");
// 3.替换:将红色替换成蓝色
h2.classList.replace("red","blue");
// 添加背景色蓝色
h2.style.backgroundColor = "green";
// 拿到这个颜色的color值,返回是blue
console.log(h2.className);
// 拿到这个元素hello word的高和宽
console.log(h2.hight);
console.log(h2.width);
// 因为"-"是非法标识符所以要去掉,S大写变成驼峰式
console.log(h2.style.fontSize);
// 计算属性
// (获取那个元素的样式,支持伪元素)
let styles=window.getComputedStyle(h2,null);
console.log(styles);
// 拿到当前元素的所有样式,不局限styles内联样式
// 拿到高度
console.log(styles.getPropertyValue("height"));
console.log(styles.getPropertyValue("width"));
</script>
</html>