免费获取API地址的网站:https://api.apiopen.top
async和await的用法
(
async function loadDate(){
let response = await fetch("https://api.apiopen.top/api/getMiniVideo?page=0&size=20")
let data = await response.json() //转换为json
data = data.result.list //转换为数组array
console.log(data)// 在控制台打印出来data变量的值
var str = ""
data.forEach((item,idndex)=>{ //forEach遍历数组
console.log(item)
//进行拼接数据
str += `<div class="video-item">
<div class="video-img">
<img src="${item.picurl}" alt="">
</div>
<div class="video-info">
<h4>${item.title}</h4>
<h5>
<span>1 HR time</span><span>herart</span>
</h5>
</div>
</div>`
})
document.querySelector(".videolist").innerHTML = str
//然后遍历数组,将数组中的数据拼接成字符串,然后赋值给str
全部代码
<!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>
*{
margin: 0;
padding: 0;
}
body{
background-color: #000;
}
.videolist{
width: 1000px;
margin:10px auto;
display: flex;
flex-wrap: wrap;
}
.video-item{
margin-right: 20px;
margin-bottom: 20px;
position: relative;
width: 200px;
border: 2px solid #ccc;
border-radius: 10px;
}
.video-item:nth-child(5n){
/* n是计时器,表示从0开始 */
margin-right: 0;
}
.video-item img{
border-radius: 5px;
width: 200px;
height: 100%;
object-fit: contain;
}
.video-info{
position: absolute;
left: 0;
width: 100%;
bottom: 10px;
color: #fff;
padding: 0 10px;
transition: all 0.3s ease-in-out;
cursor: pointer;
}
.video-info h4,.video-info:hover h5{
transition: all 0.3s ease-in-out;
}
.video-info:hover h4,.video-info:hover h3{
transform: translateY(-30px);
}
.video-info h4{
margin-bottom: 10px;
/* 下边距为10ps */
}
</style>
</head>
<body>
<!-- 这里是HTML(基本的架构搭建) -->
<div class="videolist">
<!-- <div class="video-item">
<div class="video-img">
<img src="https://vi2.6rooms.com/live/2021/11/02/17/1032v1635844543103498190_l.jpg" alt="">
</div>
<div class="video-info">
<h4>可以击中臭宝的心~</h4>
<h5>
<span>1 HR time</span><span>herart</span>
</h5>
</div> -->
</div>
<!-- 因为是从api链接中传入的数据(动态),所以把上面注释了 -->
<!-- 这里是JavaScript脚本的使用-进行分割部分(易识别) -->
<script>
(
async function loadDate(){
let response = await fetch("https://api.apiopen.top/api/getMiniVideo?page=0&size=20")
let data = await response.json() //转换为json
data = data.result.list //转换为数组array
console.log(data)// 在控制台打印出来data变量的值
var str = ""
data.forEach((item,idndex)=>{ //forEach遍历数组
console.log(item)
//进行拼接数据
str += `<div class="video-item">
<div class="video-img">
<img src="${item.picurl}" alt="">
</div>
<div class="video-info">
<h4>${item.title}</h4>
<h5>
<span>1 HR time</span><span>herart</span>
</h5>
</div>
</div>`
})
document.querySelector(".videolist").innerHTML = str
//然后遍历数组,将数组中的数据拼接成字符串,然后赋值给str
}
)()
</script>
</body>
</html>
实现效果