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

点击表单提交按钮时显示指定div的实现方法

点击表单提交按钮显示加载动画的实现方法

1. 调整CSS,让加载动画默认隐藏

在已有的.loader样式中添加display: none;,确保页面加载时它处于隐藏状态:

.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite; /* Safari 兼容 */
  animation: spin 2s linear infinite;
  display: none; /* 默认隐藏加载动画 */
}

/* Safari 兼容动画 */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

2. 添加JavaScript监听表单提交事件

给表单设置唯一ID,通过JS监听提交动作,触发时修改加载动画的显示状态:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 120px;
  height: 120px;
  -webkit-animation: spin 2s linear infinite; /* Safari 兼容 */
  animation: spin 2s linear infinite;
  display: none; /* 默认隐藏加载动画 */
}

@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
</head>
<body>

<h2>加载动画示例</h2>

<div class="loader"></div>

<form action="https://test.domain.com" method="post" id="upgradeForm">
    <input type="submit" value="Upgrade"/>
</form>

<script>
// 获取表单和加载动画元素
const upgradeForm = document.getElementById('upgradeForm');
const loader = document.querySelector('.loader');

// 监听表单提交事件
upgradeForm.addEventListener('submit', () => {
    // 显示加载动画
    loader.style.display = 'block';
});
</script>

</body>
</html>

补充说明

  • 给表单加ID是为了精准选择元素,避免页面存在多个表单时出现冲突;如果不想用ID,也可以用document.querySelector('form[method="post"]')选择,但ID方式更可靠。
  • 点击提交按钮后,表单会正常向目标地址提交数据,同时加载动画立即显示,直到页面跳转完成。
  • 如果需要实现异步提交(不跳转页面),可以在事件函数中添加event.preventDefault()阻止默认提交行为,再配合AJAX完成数据提交。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 13:01:07