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

CSS实现网站公告栏关闭按钮对齐与点击隐藏方案

公告栏关闭按钮定位与隐藏问题解决方案

问题说明

开发网站公告栏时遇到两个核心问题:

  • 无法将关闭按钮定位到公告栏右侧常规位置,尝试margin-right、padding等属性均无效
  • 需要实现点击关闭按钮后,按钮与公告栏一同消失的最优方案

解决方案

以下是完整的实现代码:

HTML代码

<div id="dabar" class="hideonload"></div>

CSS代码

/* 顶部公告栏 */
#dabar {
  background: #1b1c1e;
  color: #fff;
  font-size: 14px;
  position: fixed;
  z-index: 1;
  top: 0px;
  left: 0px;
  width: 100% !important;
  padding: 10px 0px;
  text-align: center;
}

#dabar a {
  color: #b5e48c;
  border-bottom: 1px;
}

.btn-close {
  margin-left: calc(100vw - 48px);
  margin-top: -16px;
  border: 0;
  padding: 0;
  background: red;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  flex-flow: nowrap;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 150ms;
}

.btn-close .icon-cross {
  margin: 0;
  padding: 0;
  border: 0;
  background: none;
  position: relative;
  width: 15px;
  height: 15px;
}

.btn-close .icon-cross:before,
.btn-close .icon-cross:after {
  content: '';
  position: absolute;
  top: 6.5px;
  left: 0;
  right: 0;
  height: 2px;
  background: #fff;
  border-radius: 2px;
}

.btn-close .icon-cross:before {
  transform: rotate(45deg);
}

.btn-close .icon-cross:after {
  transform: rotate(-45deg);
}

.btn-close .icon-cross span {
  display: block;
}

.btn-close:hover,
.btn-close:focus {
  transform: rotateZ(90deg);
  background: #05c;
}

JavaScript代码

// 页面加载完成后执行
window.onload = function() {
  setTimeout(func1, 2500);
};

function func1() {
  var el = document.getElementById('dabar');
  el.innerHTML = '<a href="https://imthemoisturizer.com/hola">从这里开始(西语)</a> | <a href="https://imthemoisturizer.com/en/hi">从这里开始(英语)</a><button class="btn-close" onclick="this.parentElement.style.display=\'none\'" ><span class="icon-cross"></span></button>';
  el.className = 'showtopbar';
}

注:可查看在线运行效果验证实现逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:39:14