You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为onclick按钮设置多功能,实现每次点击展示不同消息

实现点击按钮单条切换消息的方案

1. 页面结构代码

<!-- 交互按钮 -->
<button id="messageBtn">点击切换介绍</button>
<!-- 消息展示容器,初始可以放默认内容 -->
<div id="messageBox">点击按钮查看我的更多信息~</div>

2. 交互逻辑代码

直接把这段JS放在页面<body>标签的末尾即可,核心逻辑是每次点击直接覆盖展示容器的内容,不会保留历史消息:

// 替换成你自己想要展示的所有消息内容
const myMessages = [
  "哈喽~我是这个站的站长",
  "最近沉迷做复古风个人主页",
  "爱好是收集千禧年的网页素材",
  "欢迎来找我交换友链呀",
  "摸鱼的时候喜欢玩独立游戏"
]

const switchBtn = document.getElementById('messageBtn')
const showArea = document.getElementById('messageBox')

switchBtn.addEventListener('click', function() {
  // 随机抽取一条消息展示,要按顺序循环的话可以替换成下方注释的代码
  const randomIndex = Math.floor(Math.random() * myMessages.length)
  showArea.textContent = myMessages[randomIndex]

  /* 按顺序循环切换的逻辑
  let currentIndex = Number(showArea.dataset.nowIndex || 0)
  currentIndex = (currentIndex + 1) % myMessages.length
  showArea.textContent = myMessages[currentIndex]
  showArea.dataset.nowIndex = currentIndex
  */
})

3. 可选美化样式

可以把这段CSS放到你页面的<style>标签里调整外观:

#messageBtn {
  background: #c8e6c9;
  border: 2px solid #4caf50;
  padding: 6px 14px;
  border-radius: 4px;
  cursor: pointer;
}
#messageBox {
  margin: 12px 0;
  padding: 8px;
  border-left: 3px solid #4caf50;
}
  • 所有代码可以直接嵌入你的Neocities页面的个人介绍板块,不需要额外依赖。

内容的提问来源于stack exchange,提问作者omori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:15:03