<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>dataset对象</title>
</head>
<body>
<!--
* 1. 预定义:id,class,style,title...
* 2. 自定义:data- 前缀
-->
<!-- data-: 自定义属性的前缀 -->
<div data-email="nx99@qq.com" data-my-name="老马">我的邮箱</div>
<script>
const div = document.querySelector('div');
// console.log(div.dataset['email']);//同下
console.log(div.dataset.email);
//my-name:转为小驼:myName
console.log(div.dataset.myName)
</script>
</body>
</html>
关键问题:
1.找到元素
2.操作元素的行内样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>操作CSS</title>
<style>
div{
width: 200px;
height: 50px;
}
</style>
</head>
<body>
<div style="color:red;background-color:lightblue">hello world</div>
<script>
//获取行内样式style
const div = document.querySelector('div');
console.log(div.style.color);
console.log(div.style.backgroundColor);
//文档样式用style获取不到
// console.log(div.style.width)
//一个元素,最终样式,也叫计算样式,是由多个类型的样式构成:外部、文档、行内样式
//拿到一个元素的计算样式:getComputedStyle(元素)
console.log(window.getComputedStyle(div).width);
//取数值
let width = window.getComputedStyle(div).width;
width = parseInt(width);
console.log(width,typeof width);
//给Div增加宽度,修改div的行内样式
div.style.width = width + 100 + 'px';
console.log(window.getComputedStyle(div).width);
</script>
</body>
</html>
方法:
1.add():添加
2.remove():移除
3.replace():替换
4.toggle():切换
5.contains():判断
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>classList对像:操作元素</title>
</head>
<body>
<h1>hello world!</h1>
<style>
.red {
color:red;
}
.blue {
color:blue;
}
.bgc {
background-color: yellow;
}
</style>
<script>
//classList:管理元素的class属性
const h1 = document.querySelector('h1');
//1. 添加:add()
// h1.classList.add('red');
// h1.classList.add('blue','bgc');
const styles = ['red','bgc'];
h1.classList.add(...styles);
//2.判断:contains()
// 判断是否有某个样式 console.log(h1.classList.contains('bgc'))
//3.替换:replace()
h1.classList.replace('red','blue');
//4.移除: remove()
h1.classList.remove('blue','bgc');
//5.切换:toggle()
//切换:有该class,就remove();没有就add();
h1.classList.toggle('red');
h1.classList.toggle('red');
</script>
</body>
</html>