You need to enable JavaScript to run this app. 如何为特定按钮禁用页面刷新后的高度重置效果
优惠活动
大模型
产品
解决方案
定价
更多

如何为特定按钮禁用页面刷新后的高度重置效果

解决方案

你需要把按钮的高度状态持久化存储在浏览器本地,页面刷新后读取存储值覆盖默认样式即可,具体实现逻辑如下:

  • 给目标按钮设置唯一ID,方便DOM操作
  • 页面加载时优先读取localStorage中存储的按钮高度值,有值则直接赋值给按钮样式,无值则使用默认的150px
  • 按钮点击事件中修改高度为300px的同时,将高度值写入localStorage做持久化

完整可运行代码示例:

<button id="customBtn" style="height: 150px;">测试按钮</button>

<script>
const customBtn = document.getElementById('customBtn')
// 初始化读取存储的高度
const storedHeight = localStorage.getItem('customBtnHeight')
if (storedHeight) {
  customBtn.style.height = storedHeight
}
// 点击事件
customBtn.onclick = function() {
  const targetHeight = '300px'
  this.style.height = targetHeight
  localStorage.setItem('customBtnHeight', targetHeight)
}
</script>

如果需要实现点击切换高度(再次点击回到150px),只需要在点击事件中判断当前高度,修改存储值即可。

如果你需要关闭浏览器后状态就重置,可以把localStorage替换为sessionStorage,二者API用法完全一致,区别仅在于存储的生命周期不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 15:27:02