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

如何为Flask应用的HTML按钮点击事件正确调用CSS加载器

正确调用加载器的解决方案

问题分析

你的现有代码存在三个核心问题:

  1. 加载器默认处于显示状态,页面一加载就会出现,不符合“点击提交后才显示”的需求
  2. 使用onclick绑定事件可能因表单提交速度过快,导致加载器来不及显示就跳转页面
  3. 未确保jQuery已正确引入,$("#loader")可能无法生效

步骤1:修正加载器CSS

给加载器添加默认隐藏属性,同时设置居中定位和层级,确保显示时不被遮挡:

#loader {
  border: 16px solid #f3f3f3; /* Light grey */
  border-top: 16px solid #3498db; /* Blue */
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 2s linear infinite;
  display: none; /* 默认隐藏加载器 */
  position: fixed; /* 固定在视窗中 */
  top: 50%;
  left: 50%;
  margin-top: -60px; /* 垂直居中:高度的一半负值 */
  margin-left: -60px; /* 水平居中:宽度的一半负值 */
  z-index: 9999; /* 确保加载器在最上层 */
}

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

步骤2:修改Flask模板代码

  • 确保引入jQuery(建议将jQuery文件放在项目static/js目录下)
  • 改用jQuery绑定表单提交事件,替代onclick,提升稳定性
{% extends "base.html" %}
{% block head %}
  <!-- 引入本地jQuery文件 -->
  <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
  <!-- 加载器样式 -->
  <style>
    #loader {
      border: 16px solid #f3f3f3;
      border-top: 16px solid #3498db;
      border-radius: 50%;
      width: 120px;
      height: 120px;
      animation: spin 2s linear infinite;
      display: none;
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -60px;
      margin-left: -60px;
      z-index: 9999;
    }
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }
  </style>
{% endblock %}
{% block content %}
<div id="loader"></div>
<div id="vo_budget_file_settings">
    <p>Please upload the final CRO budget File</p>
    <form action="/generatecleanbudgetfile" method=POST enctype=multipart/form-data id="budgetForm">
        <input type="file" name="data_file" accept=".xls, .xlsx, .xlsm"/>
        <input type="submit" value="Begin Format"/>
    </form>
</div>
<script type="text/javascript">
    $(document).ready(function() {
        // 绑定表单提交事件
        $("#budgetForm").submit(function() {
            $("#loader").show(); // 显示加载器
            return true; // 允许表单正常提交到后端
        });
    });
</script>
{% endblock %}

关键说明

  • 加载器默认隐藏,只有点击提交按钮触发表单提交时才会显示
  • 固定定位确保加载器始终在页面中央,不会随滚动条移动
  • 使用表单submit事件绑定比onclick更可靠,能避免因提交过快导致加载器不显示的问题
  • 必须确保jQuery已正确引入,否则所有jQuery语法都无法生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:48:18