使用 setInterval 实现定时轮换(最简单)

这是最基础的方法,通过定时器每隔一段时间就更换一次要显示的文字。

js实现网页实时显示不同的话
(图片来源网络,侵删)

核心思路:

  1. 准备一个包含多条文字的数组。
  2. 使用 setInterval() 设置一个定时器,比如每2秒执行一次。
  3. 在定时器的回调函数中,按顺序(或随机)从数组中取出一条文字。
  4. 使用 document.getElementById() 找到网页上对应的元素(比如一个 <p><div>)。
  5. element.textContentelement.innerHTML 将新文字显示在页面上。

完整代码示例

你可以直接将以下代码保存为一个 .html 文件,然后用浏览器打开即可看到效果。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">JS 实时显示不同的话</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f0f2f5;
            margin: 0;
        }
        .message-container {
            text-align: center;
            padding: 40px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            max-width: 500px;
        }
        h1 {
            color: #333;
        }
        #message-display {
            font-size: 1.5em;
            color: #007bff;
            margin-top: 20px;
            min-height: 40px; /* 防止文字变化时布局跳动 */
            transition: opacity 0.3s ease-in-out; /* 添加淡入淡出效果 */
        }
    </style>
</head>
<body>
    <div class="message-container">
        <h1>每日一句</h1>
        <p id="message-display">正在加载...</p>
    </div>
    <script>
        // 1. 准备一个包含多条文字的数组
        const messages = [
            "生活不是等待暴风雨过去,而是学会在雨中跳舞。",
            "你的时间有限,不要浪费在重复别人的生活上。",
            "唯一不可能的事,就是你不去尝试的事。",
            "成功不是终点,失败也并非末日,最重要的是继续前进的勇气。",
            "每一个不曾起舞的日子,都是对生命的辜负。",
            "千里之行,始于足下。",
            "天行健,君子以自强不息。"
        ];
        // 2. 获取要显示文字的DOM元素
        const messageElement = document.getElementById('message-display');
        let currentIndex = 0; // 用于追踪当前显示的是第几条消息
        // 3. 创建一个函数来更新显示的文字
        function updateMessage() {
            // 淡出效果
            messageElement.style.opacity = '0';
            // 等待淡出动画完成后,再更新文字并淡入
            setTimeout(() => {
                // 从数组中取出当前索引的文字
                messageElement.textContent = messages[currentIndex];
                // 更新索引,确保循环
                currentIndex = (currentIndex + 1) % messages.length;
                // 淡入效果
                messageElement.style.opacity = '1';
            }, 300); // 这个时间要和CSS中的transition时间匹配
        }
        // 4. 使用 setInterval 设置定时器,每2秒调用一次 updateMessage 函数
        setInterval(updateMessage, 2000);
        // 立即执行一次,避免等待2秒才显示第一条
        updateMessage();
    </script>
</body>
</html>

从服务器实时获取数据(AJAX / Fetch API)

在很多实际应用中,“不同的话”并不是预先写好的,而是存储在服务器数据库里的,比如新闻标题、用户评论、聊天消息等,这时就需要从服务器动态获取数据。

核心思路:

js实现网页实时显示不同的话
(图片来源网络,侵删)
  1. 前端使用 fetch API 定期向后端 API 发送请求。
  2. 后端 API 接收到请求,从数据库查询最新的一条或几条数据。
  3. 后端将数据以 JSON 格式返回给前端。
  4. 前端接收到数据后,将其解析并显示在页面上。

模拟后端和前端的完整示例

由于我们无法在这里真正运行一个后端服务器,我将使用一个公共的 API(JSONPlaceholder)来模拟这个场景,我们将获取这个 API 提供的“帖子”标题作为我们实时显示的“话”。

前端代码 (HTML + JS)

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">从服务器实时获取数据</title>
    <style>
        body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #e9ecef; margin: 0; }
        .post-container { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); text-align: center; }
        #post-title { font-size: 1.3em; color: #495057; margin-top: 15px; font-weight: bold; }
        #loading { color: #6c757d; font-style: italic; }
    </style>
</head>
<body>
    <div class="post-container">
        <h1>服务器最新动态</h1>
        <p id="loading">正在从服务器加载...</p>
        <h2 id="post-title"></h2>
    </div>
    <script>
        const postTitleElement = document.getElementById('post-title');
        const loadingElement = document.getElementById('loading');
        // 模拟从服务器获取最新帖子标题的函数
        async function fetchLatestPostTitle() {
            // 显示加载状态
            loadingElement.style.display = 'block';
            postTitleElement.textContent = '';
            try {
                // 使用 fetch API 调用公共 API
                // 为了模拟“不同”的数据,我们每次请求一个随机的 ID (1 到 100)
                const randomId = Math.floor(Math.random() * 100) + 1;
                const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${randomId}`);
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                const postData = await response.json();
                // 隐藏加载状态,并显示获取到的标题
                loadingElement.style.display = 'none';
                postTitleElement.textContent = postData.title;
            } catch (error) {
                console.error('获取数据失败:', error);
                loadingElement.style.display = 'none';
                postTitleElement.textContent = '无法加载数据,请稍后再试。';
            }
        }
        // 每3秒从服务器获取一次新数据
        setInterval(fetchLatestPostTitle, 3000);
        // 立即执行一次
        fetchLatestPostTitle();
    </script>
</body>
</html>

使用 WebSocket 实现真正的实时通信

这是“实时”的终极形态,适用于聊天室、在线游戏、股票行情等场景,服务器可以主动向客户端推送数据,而不需要客户端不停地轮询(Polling)。

核心思路:

  1. 前端创建一个 WebSocket 连接到服务器。
  2. 服务器维护一个 WebSocket 连接池。
  3. 当有新数据时(比如一个用户发了一条新消息),服务器通过 WebSocket 连接主动将该数据推送给所有在线的客户端。
  4. 前端通过监听 onmessage 事件来接收服务器推送过来的数据并更新页面。

简单的 WebSocket 示例

同样,我们无法在这里运行一个真正的 WebSocket 服务器,但我们可以用一个简单的 HTML 文件来模拟客户端,并使用一个公共的 WebSocket 测试服务(如 ws://echo.websocket.org)来演示其工作原理,这个服务会把你发给它的消息再发回来。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">WebSocket 实时通信</title>
    <style>
        body { font-family: sans-serif; padding: 20px; background-color: #2c3e50; color: white; }
        #messages { list-style-type: none; margin: 0; padding: 0; border: 1px solid #34495e; height: 300px; overflow-y: auto; background: #34495e; padding: 10px; border-radius: 5px; }
        #messages li { padding: 5px 10px; margin-bottom: 5px; background: #1abc9c; border-radius: 3px; }
        #form { display: flex; margin-top: 10px; }
        #input { flex-grow: 1; padding: 10px; border: none; border-radius: 3px 0 0 3px; }
        button { padding: 10px 15px; border: none; background: #e74c3c; color: white; cursor: pointer; border-radius: 0 3px 3px 0; }
        button:hover { background: #c0392b; }
        #status { margin-top: 10px; font-style: italic; color: #95a5a6; }
    </style>
</head>
<body>
    <h1>WebSocket 聊天室模拟</h1>
    <p id="status">正在连接到服务器...</p>
    <ul id="messages"></ul>
    <form id="form">
        <input id="input" autocomplete="off" /><button>发送</button>
    </form>
    <script>
        const form = document.getElementById('form');
        const input = document.getElementById('input');
        const messages = document.getElementById('messages');
        const status = document.getElementById('status');
        // 1. 创建 WebSocket 连接
        // 使用一个公共的 echo 服务器来测试
        const ws = new WebSocket('ws://echo.websocket.org');
        ws.onopen = function(event) {
            status.textContent = '连接已建立!';
            status.style.color = '#2ecc71';
        };
        ws.onclose = function(event) {
            status.textContent = '连接已关闭。';
            status.style.color = '#e74c3c';
        };
        // 2. 监听来自服务器的消息
        ws.onmessage = function(event) {
            // event.data 服务器发来的数据
            const li = document.createElement('li');
            li.textContent = `服务器回复: ${event.data}`;
            messages.appendChild(li);
            window.scrollToBottom();
        };
        ws.onerror = function(error) {
            status.textContent = `连接发生错误: ${error.message}`;
            status.style.color = '#f39c12';
        };
        // 3. 处理表单提交,向服务器发送消息
        form.addEventListener('submit', function(e) {
            e.preventDefault(); // 阻止表单默认的提交行为(页面刷新)
            if (input.value) {
                const li = document.createElement('li');
                li.textContent = `你发送: ${input.value}`;
                li.style.textAlign = 'right';
                li.style.background = '#3498db';
                messages.appendChild(li);
                // 通过 WebSocket 发送消息
                ws.send(input.value);
                input.value = '';
                window.scrollToBottom();
            }
        });
        // 一个辅助函数,让消息列表自动滚动到底部
        window.scrollToBottom = function() {
            messages.scrollTop = messages.scrollHeight;
        };
    </script>
</body>
</html>

总结与对比

方法 优点 缺点 适用场景
setInterval 简单、直观,无需后端。 数据是静态的,无法动态更新;频繁轮询可能浪费资源。 轮播图、展示固定的名言警句、产品特性介绍等。
AJAX / Fetch 数据动态,可以与后端数据库交互。 客户端主动轮询,服务器压力大,实时性稍差(有延迟)。 新闻列表、博客文章、动态加载的商品列表等。
WebSocket 真正的实时,服务器可主动推送,效率高,延迟低。 需要后端支持 WebSocket 服务,实现相对复杂。 聊天应用、在线协作工具、实时通知、股票行情、在线游戏。

对于初学者,方法一是最好的起点,当你需要与后端交互时,方法二是标准做法,如果你需要构建高实时性的应用,方法三是不二之选。