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

公告栏关闭按钮失效(ReferenceError)及页面内容位移问题求助

问题修复方案

1. 解决控制台报错与关闭按钮失效问题

你把JS代码放在了<style type="text/javascript">标签里,这是错误的——<style>标签仅用于存放CSS样式,JavaScript代码必须放在<script>标签中。修改后JS代码才能被正确解析,函数也能被正常调用。

2. 实现公告栏显示/隐藏时的页面推送效果

直接修改display属性会让元素瞬间从文档流中消失/出现,无法实现平滑的推送效果。建议通过切换CSS类的方式,结合过渡动画来实现:

完整修改后的代码

HTML + JavaScript

<body>
    <!-- announcement bar -->
    <div class="announcement-bar" id="announcement-bar">
        <div class="announcement-bar-content">
            <p>I am currently available for work.</p>
        </div>
        <button class="announcement-bar-close-btn" onclick="toggleAnnouncementBar()">
            <i class="fas fa-times"></i>
        </button>
    </div>

    <div class="container">
        <!-- 页面内容 -->
    </div>

    <script>
        function toggleAnnouncementBar() {
            const announcementBar = document.getElementById("announcement-bar");
            const container = document.querySelector(".container");
            
            announcementBar.classList.toggle("hidden");
            container.classList.toggle("announcement-pushed");
        }
    </script>
</body>

CSS

/* announcement bar */
.announcement-bar {
    background: #FDFDFD;
    height: 45px;
    width: 100%;
    transition: height 0.3s ease;
    overflow: hidden;
}

/* 隐藏状态的公告栏 */
.announcement-bar.hidden {
    height: 0;
}

.announcement-bar-content {
    padding: 10px;
    width: 95%;
    float: left;
    height: 45px;
    color: #fff;
    text-align: center;
    text-transform: uppercase;
}

.announcement-bar-content p {
    font-family: "IBM Plex Mono";
    font-size: 0.9rem;
    font-weight: 600;
    color: #2B3030;
}

.announcement-bar-content a {
    color: #fff;
}

button.announcement-bar-close-btn {
    height: 100%;
    width: 5%;
    background: #2B303080;
    color: #2B3030;
    border: none;
    cursor: pointer; /* 添加鼠标指针样式,提升交互体验 */
}

/* 页面内容被推送的状态 */
.container.announcement-pushed {
    margin-top: 0;
}

.container {
    margin-top: 45px; /* 初始状态下,给内容区添加与公告栏高度一致的上边距 */
    transition: margin-top 0.3s ease;
}

.hello-pop-work {
    text-decoration: underline;
    padding: 0 5px 0 5px;
}

关键修改点说明

  • 将JS代码的容器从<style>改为<script>,修复myFunction is not defined报错;
  • 给公告栏添加hidden类,通过修改高度而非display属性实现平滑隐藏/显示;
  • 给.container设置初始margin-top等于公告栏高度,切换类时修改该值,实现页面内容的推送效果;
  • 添加transition属性,让高度和边距变化有平滑的动画过渡;
  • 给关闭按钮添加cursor: pointer,提升交互体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:01:02