当前位置: 首页 > news >正文

博客无限滚动加载(html、css、js)实现

介绍

这是一个简单实现了类似博客瀑布流加载功能的页面,使用html、css、js实现。简单易懂,值得学习借鉴。👍

演示地址:https://i_dog.gitee.io/easy-web-projects/infinite_scroll_blog/index.html

代码

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的博客</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>博客</h1>
    <div class="filter-container">
        <input type="text" class="filter" id="filter" placeholder="搜索文章">
    </div>
    <div id="posts-container"></div>
    
    <div class="loader">
        <div class="circle"></div>
        <div class="circle"></div>
        <div class="circle"></div>
    </div>

    <script src="script.js"></script>
</body>
</html>

style.css

/* 从Google Fonts(谷歌字体)中导入名为"Roboto"的字体,并将其应用于网页中的文本内容。 */
@import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');

* {
    box-sizing: border-box;
}

body {
    background-color: #296ca8;
    font-family: 'Roboto', sans-serif;
    display: flex;
    flex-direction: column;
    color: #fff;
    /* 元素在侧轴居中。 */
    align-items: center;

    /* 伸缩元素向每主轴中点排列。 */
    justify-content: center;

    min-height: 100vh;
    margin: 0;
    padding-bottom: 100px;
}
h1 {
    margin-bottom: 20px;
    text-align: center;
}
.filter-container {
    margin-top: 20px;
    width: 80vw;
    max-width: 800px;
    /* border: 1px solid black; */
}
.filter {
    width: 100%;
    padding: 12px;
    font-size: 16px;
}

.post {
    position: relative;
    background: #4992d3;

    /* 
        创建一个元素的阴影效果
        水平偏移量 垂直偏移量 阴影的模糊半径  阴影的颜色和透明度
    */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    border-radius: 3px;
    padding: 20px;
    margin: 40px 0;
    display: flex;
    width: 80vw;
    max-width: 800px;
}

.post .post-title {
    margin: 0;
}
.post .post-body {
    margin: 15px 0 0;
    line-height: 1.3;
}

.post .post-info {
    margin-left: 20px;
}
.post .number {
    position: absolute;
    top: -15px;
    left: -15px;
    font-size: 15px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #fff;
    color: #296ca8;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 7px 10px;
  }
.loader {
    /* 默认透明 */
    opacity: 0;
    display: flex;
    position: fixed;
    bottom: 50px;
    /* 
        添加过渡效果
        要过渡的CSS属性   过渡的持续时间   过渡的速度曲线
    */
    transition: opacity 0.3s ease-in;
}
.loader.show {
    opacity: 1;
}
.circle {
    background-color: #fff;
    width: 10px;
    height: 10px;

    /* 呈现出一个完整的圆形形状 */
    border-radius: 50%;
    margin: 5px;

    /* 
        添加动画效果 
        应用的动画名称  动画的持续时间  动画的速度曲线  动画循环播放
    */
    animation: bounce 0.5s ease-in infinite;
}

/* 选择文档中第一个类名为"circle"的元素 */
.circle:nth-of-type(2) {
    animation-delay: 0.1s;
}
.circle:nth-of-type(3) {
    animation-delay: 0.2s;
}

@keyframes bounce {
    0%,
    100% {
        transform: translateY(0);    
    }
    50% {
        transform: translateY(-10px);
    }
}

script.js

const postsContainer = document.getElementById('posts-container')
// 获取文档中具有类名"loader"的第一个元素
const loading = document.querySelector('.loader')
const filter = document.getElementById('filter')

let limit = 5
let page = 1

// 从API获取博客
async function getPosts() {
    // 使用await关键字等待fetch()函数返回的Promise对象,
    // 这个Promise对象表示服务器响应的结果。
    const res = await fetch(
        `https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`
    )

    // 使用res.json()方法将响应体解析为JSON格式的数据。
    const data =  await res.json()
    
    return data
}

// 在DOM中展示博客列表
async function showPosts() {
    const posts = await getPosts()

    posts.forEach(post => {
        const postEl = document.createElement('div')
        postEl.classList.add('post')
        postEl.innerHTML = `
            <div class="number">${post.id}</div>
            <div class="post-info">
                <h2 class="post-title">${post.title}</h2>
                <p class="post-body">${post.body}</p>
            </div>
        `
        postsContainer.appendChild(postEl)
    })
}

// 展示加载动画并且获取其他博客
function showLoading() {
    loading.classList.add('show')

    setTimeout(() => {
        loading.classList.remove('show')

        setTimeout(() => {
            page++
            showPosts()
        },300)
        

    },1000)
}

// 搜索框查找博客
function filterPosts(e) {
    const term = e.target.value.toUpperCase()
    const posts = document.querySelectorAll('.post')

    posts.forEach(post => {
        const title = post.querySelector('.post-title').innerText.toUpperCase()
        const body = post.querySelector('.post-body').innerText.toUpperCase()

        if(title.indexOf(term) > -1 || body.indexOf(term) > -1) {
            post.style.display = 'flex'
        } else {
            post.style.display = 'none'
        }
    })
    // console.log('Filtering posts...');
}

// 获取初始博客
showPosts()

window.addEventListener('scroll', () => {
    // scrollTop属性表示文档在垂直方向上滚动的距离,
    // scrollHeight属性表示文档内容的总高度,
    // clientHeight属性表示可视区域的高度。
    const {scrollTop, scrollHeight, clientHeight} = document.documentElement

    if (scrollTop + clientHeight >= scrollHeight - 5) {
        showLoading()
    }
})

filter.addEventListener('input', filterPosts)

补充

该项目从github中的vanillawebprojects仓库收集。

原始代码:原始代码地址icon-default.png?t=N7T8https://github.com/bradtraversy/vanillawebprojects/tree/master/infinite_scroll_blog

本文代码:本文代码地址icon-default.png?t=N7T8https://gitee.com/i_dog/easy-web-projects/tree/master/infinite_scroll_blog

相关文章:

  • 简化数据库操作:探索 Gorm 的约定优于配置原则
  • javaWeb学生信息管理
  • 读书笔记|《数据压缩入门》—— 柯尔特·麦克安利斯 亚历克斯·海奇
  • 网盘搜索引擎:点亮知识星空,畅享数字宝藏!
  • 【NLP的python库(03/4) 】: 全面概述
  • netty 拆包/粘包
  • 冥想第九百二十九天
  • 获取网卡上的IP、网关及DNS信息,获取最佳路由,遍历路由表中的条目(附源码)
  • 保姆级 -- Zookeeper超详解
  • watch()监听vue2项目角色权限变化更新挂载
  • 【图论C++】树的重心——教父POJ 3107(链式前向星的使用)
  • 为什么炒股人更爱融资?融券交易背后的风险与获利机会
  • Springboot实现websocket(连接前jwt验证token)
  • 一篇博客学会系列(3) —— 对动态内存管理的深度讲解以及经典笔试题的深度解析
  • PyTorch应用实战一:实现卷积操作
  • Pytorch梯度累积实现
  • 红米手机 导出 通讯录 到电脑保存
  • 【算法基础】基础算法(一)--(快速排序、归并排序、二分)
  • [MAUI程序设计] 用Handler实现自定义跨平台控件
  • 黑豹程序员-CSS四种样式的定义方式及冲突后的就近原则
  • 儿童阅读空间、残疾人友好书店……上海黄浦如何打造城市书房
  • 新消费观察 | 重点深耕,外资科技企业继续看好中国发展
  • 同程旅行:拟24.97亿元收购万达酒管100%股权
  • 青创上海-2025浦东徒步行倒计时1天,明日浦东世博文化公园不见不散
  • 2025年上海版权宣传周在杨浦启动
  • 上海不重视民企?专家:此次26项措施消除了误会,信心比黄金重要