前言
记录时间:2023.3.15
坚持的第十七天
JavaScript从入门到精通
学习javascript时间历程记录打卡
晚上8:30到22:30
JS基础web APIs总结
完成代码练习
1.随机显示图片
<!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>Document</title>
</head>
<body>
<img src="./images/1.webp" >
<script>
// 取到 N ~ M 的随机整数
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N
}
// 1. 获取图片对象
const img = document.querySelector('img')
// 2. 随机得到序号
const random = getRandom(1, 6)
// 3. 更换路径
img.src = `./images/${random}.webp`
</script>
</body>
</html>
2.通过style属性修改样式
<!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>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
// 1. 获取元素
const box = document.querySelector('.box')
//2. 修改样式属性 对象.style.样式属性 = '值' 别忘了跟单位
box.style.width = '300px'
// 多组单词的采取 小驼峰命名法
box.style.backgroundColor = 'hotpink'
box.style.border = '2px solid blue'
box.style.borderTop = '2px solid red'
</script>
</body>
</html>
3.随机更换背景图片
<!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>Document</title>
<style>
body {
background: url(./images/desktop_1.jpg) no-repeat top center/cover;
}
</style>
</head>
<body>
<script>
// console.log(document.body)
// 取到 N ~ M 的随机整数
function getRandom(N, M) {
return Math.floor(Math.random() * (M - N + 1)) + N
}
// 随机数
const random = getRandom(1, 10)
document.body.style.backgroundImage = `url(./images/desktop_${random}.jpg)`
</script>
</body>
</html>
4.通过类名修改样式
<!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>Document</title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
.nav {
color: red;
}
.box {
width: 300px;
height: 300px;
background-color: skyblue;
margin: 100px auto;
padding: 10px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="nav">123</div>
<script>
// 1. 获取元素
const div = document.querySelector('div')
// 2.添加类名 class 是个关键字 我们用 className
div.className = 'nav box'
</script>
</body>
</html>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
暂无评论内容