<!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>相册</title>
<style>
/* 通用样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
li {
list-style: none;
}
a {
text-decoration: none;
}
.container {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
}
.container > .butgirl {
width: 13rem;
border: 1px solid green;
padding: 0.5rem;
margin-top: 0.5rem;
}
.container > .butgirl > img {
width: 100%;
}
/* 按钮 */
.container > .butgirl > .btn {
display: flex;
justify-content: space-between;
margin-top: 0.5rem;
}
.container > .butgirl > .btn > button {
background-color: green;
height: 1.5rem;
border-radius: 0.5rem;
border: none;
flex: 0 1 31%;
}
</style>
</head>
<body>
<div class="container"></div>
<script>
let imgsGroup = [
"images/img-1.jpg",
"images/img-4.jpg",
"images/img-8.jpg",
"images/img-16.jpg",
"images/img-24.jpg",
"images/img-20.jpg",
"images/img-25.jpg",
"images/img-39.jpg",
];
// 获取图片容器
let container = document.querySelector(".container");
//当页面加载完成之后显示图片
window.onload = showImgs;
//图片展示方法
function showImgs() {
let res = imgsGroup.reduce(function (prev, curr) {
let html = `
<div class="butgirl">
<img src="${curr}" />
<div class="btn">
<button onclick=goBefer(this)>向前</button>
<button onclick=goAfter(this)>向后</button>
<button onclick=goDel(this)>删除</button>
</div>
</div>
`;
return prev + html;
}, "");
container.insertAdjacentHTML("afterbegin", res);
}
//图片向前
function goBefer(obj) {
//获取点击的图片元素
let father = obj.parentNode.parentNode;
//点击的图片元素的上一个兄弟元素
let befor = father.previousElementSibling;
// console.log(befor);
if (befor == null) {
alert("不能向前了!");
return false;
}
// 将兄弟元素插入到点击元素之前
container.insertBefore(father, befor);
}
// 图片向后
function goAfter(obj) {
//获取点击的图片元素
let father = obj.parentNode.parentNode;
//点击的图片元素的下一个兄弟元素
let next = father.nextElementSibling;
// console.log(befor);
if (next == null) {
alert("不能向后了!");
return false;
}
// 将点击元素插入到兄弟元素之后
// dom只提供了
container.insertBefore(next, father);
}
// 图片删除
function goDel(obj) {
let father = obj.parentNode.parentNode;
if (confirm("是否删除?")) father.remove();
}
</script>
</body>
</html>