前言
在 Github 上发现有老哥在仓库里放了很多图片(表情包),想着一个一个找比较不方便就用js码了个图片展示页面,主要是用来展示一个从 GitHub 仓库上获取的图片,其实很简单,就是通过js调用Github的接口来实现这一功能。
主要代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>在线图片</title>
<style>
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 10px;
}
.category {
margin-bottom: 20px;
}
.category h2 {
text-align: center;
}
.image {
width: 100%;
height: auto;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="gallery"></div>
<script>
async function fetchImages() {
const response = await fetch('https://api.github.com/repos/{用户名}/{仓库名}/contents/');
const data = await response.json();
let gallery = document.getElementById('gallery');
// 遍历文件夹,创建分类块
for (const item of data) {
if (item.type === 'dir') {
const folderName = item.name;
const folderResponse = await fetch(item.url);
const folderData = await folderResponse.json();
// 创建分类容器
const categoryDiv = document.createElement('div');
categoryDiv.className = 'category';
const title = document.createElement('h2');
title.innerText = folderName;
categoryDiv.appendChild(title);
const containerDiv = document.createElement('div');
containerDiv.className = 'container';
// 遍历图片文件
for (const file of folderData) {
if (file.name.endsWith('.jpg') || file.name.endsWith('.png')) {
const img = document.createElement('img');
img.className = 'image';
img.src = file.download_url;
containerDiv.appendChild(img);
}
}
categoryDiv.appendChild(containerDiv);
gallery.appendChild(categoryDiv);
}
}
}
fetchImages();
</script>
</body>
</html>
以上代码可以优化的地方还比较多。
比如添加显示的图片 gif
可以将代码:
if (file.name.endsWith('.jpg') || file.name.endsWith('.png')) {
改为:
if (file.name.endsWith('.jpg') || file.name.endsWith('.png') || file.name.endsWith('.gif')) { 还可以过来需要显示或者不显示的文件夹
if (item.type === 'dir') { 改为:
if (item.type === 'dir'&& item.name !== 'QQ' && item.name !== 'picture') { 表示为不显示 QQ 、picture 文件夹下图片
如果图片在国内访问比较慢,可以使用别人建好的GitHub反代来加速
img.src = file.download_url;
改为:
img.src = "http://gh.chaoyi996.com/"+file.download_url;
最后的/不能少,github 文件加速合集:https://github-mirror.us.kg/
如何使用
GitHub仓库存储图片需按目录分类,在网页显示也是按目录分类,以目录名称为分类名修改代码中的api 接口链接。
https://api.github.com/repos/{用户名}/{仓库名}/contents/ 如:
https://api.github.com/repos/getActivity/EmojiPackage/contents/
可以优化的地方还是比较多,比如:
- 数据缓存到本地,减少对GitHub接口的请求数量
- 图片懒加载
- 页面分页或者流加载
- 其他各种美化
参考网页
这是我这边实现的两个网页,大家可以查看源代码参考一下。
