新增第247个小实例:图片九宫格

This commit is contained in:
DESKTOP-BM6RJU5\wyanh 2024-04-26 11:20:26 +08:00
parent 071b23eb23
commit c46f23053b
5 changed files with 83 additions and 0 deletions

View File

@ -254,6 +254,7 @@
244. HTML5+CSS3小实例粘性文字的滚动效果
245. HTML5+CSS3小实例简约灵动的深色登录界面
246. HTML5+CSS3小实例可爱的卷纸开关
247. HTML5+CSS3+JS小实例图片九宫格
#### 赞赏作者
![image](https://gitee.com/wyanhui02/html_css_demo/raw/master/images/%E8%B5%9E%E8%B5%8F%E4%BD%9C%E8%80%85/%E8%B5%9E%E8%B5%8F%E7%A0%81.jpg)

44
code/247/247.css Normal file
View File

@ -0,0 +1,44 @@
*{
/* 初始化 */
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
/* 100%窗口宽高 */
width: 100vw;
height: 100vh;
background: linear-gradient(200deg, #fdd6bd, #f794a4);
/* 弹性布局 居中显示 */
display: flex;
justify-content: center;
align-items: center;
}
.img-container{
/* 网格布局 3行3列 间隙20px */
display: grid;
grid-template-rows: 100px 100px 100px;
grid-template-columns: 100px 100px 100px;
gap: 20px;
/* 过渡 */
transition: 0.5s ease;
}
.img-item{
width: 100px;
height: 100px;
/* 内阴影(内边框) */
box-shadow: inset 0 0 0 1px #fff;
background-image: url(/images/247.jpg);
background-size: 300px 300px;
/* 设置背景图像的起始位置,--bgX、--bgY为自定义变量后面通过JS计算并赋值 */
background-position: var(--bgX, 0) var(--bgY, 0);
/* 过渡 */
transition: 0.5s ease;
}
/* 悬停样式 */
.img-container:hover{
gap: 0;
}
.img-container:hover .img-item{
box-shadow: inset 0 0 0 0 #fff;
}

23
code/247/247.html Normal file
View File

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片九宫格</title>
<link rel="stylesheet" href="247.css">
</head>
<body>
<div class="img-container">
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
<div class="img-item"></div>
</div>
</body>
</html>
<script src="247.js"></script>

15
code/247/247.js Normal file
View File

@ -0,0 +1,15 @@
// 获取所有item
const items=document.querySelectorAll('.img-item');
// 遍历所有item
for(let i=0;i<items.length;i++){
// 第几行
const r=Math.floor(i / 3);
// 第几列
const c=i % 3;
const bgX=-c * 100 + '%';
const bgY=-r * 100 + '%';
// 设置CSS自定义变量
items[i].style.setProperty('--bgX', bgX);
items[i].style.setProperty('--bgY', bgY);
}

BIN
images/247.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB