js读取本地文件夹的图片并分页显示在页面上
时间: 2023-12-03 08:47:03 浏览: 47
要实现这个功能,你需要使用 JavaScript 和 HTML。首先,你需要使用 JavaScript 来读取本地文件夹中的所有图片,并将它们存储在一个数组中。然后,你需要将这些图片分页显示在页面上。
下面是一个简单的示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>分页显示本地文件夹的图片</title>
<style>
.page {
display: none;
}
.page.active {
display: block;
}
</style>
</head>
<body>
<div id="gallery"></div>
<div id="pagination"></div>
<script>
// 读取本地文件夹中的所有图片
const folderPath = './images/';
const images = [];
const xhr = new XMLHttpRequest();
xhr.open('GET', folderPath);
xhr.responseType = 'document';
xhr.onload = function() {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(xhr.responseXML.documentElement.outerHTML, 'text/html');
const fileList = htmlDoc.querySelectorAll('a');
for (let i = 0; i < fileList.length; i++) {
const fileName = fileList[i].textContent;
if (/\.(jpe?g|png|gif)$/i.test(fileName)) {
images.push(folderPath + fileName);
}
}
showGallery(1); // 初始化显示第一页
showPagination(); // 显示分页
};
xhr.send();
// 分页显示图片
function showGallery(page) {
const gallery = document.getElementById('gallery');
gallery.innerHTML = '';
const pageSize = 12; // 每页显示12张图片
const startIndex = (page - 1) * pageSize;
const endIndex = Math.min(startIndex + pageSize, images.length);
for (let i = startIndex; i < endIndex; i++) {
const img = document.createElement('img');
img.src = images[i];
gallery.appendChild(img);
}
}
// 显示分页
function showPagination() {
const pagination = document.getElementById('pagination');
const pageCount = Math.ceil(images.length / 12); // 计算总页数
for (let i = 1; i <= pageCount; i++) {
const pageLink = document.createElement('a');
pageLink.textContent = i;
pageLink.onclick = function() {
const activePage = document.querySelector('.page.active');
activePage.classList.remove('active');
const page = parseInt(this.textContent);
const pageElement = document.getElementById(`page-${page}`);
pageElement.classList.add('active');
showGallery(page);
};
pagination.appendChild(pageLink);
const page = document.createElement('div');
page.id = `page-${i}`;
page.classList.add('page');
if (i === 1) {
page.classList.add('active');
}
pagination.appendChild(page);
}
}
</script>
</body>
</html>
```
这个示例代码假设你的图片存储在 `./images/` 文件夹中,并且文件夹中仅包含图片文件(后缀名为 `.jpg`、`.jpeg`、`.png` 或 `.gif`)。它将读取文件夹中的所有图片,并将它们存储在 `images` 数组中。然后,它将使用 `showGallery` 函数显示第一页的图片,并使用 `showPagination` 函数显示分页。你可以根据需要自行修改文件夹路径和每页显示的图片数量。