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

如何实现特定屏幕宽度阈值下弹出指定Div弹窗

如何实现特定屏幕宽度阈值下弹出指定Div弹窗

Hey there! 别发愁啦,你的HTML和CSS已经写得很好了,只需要加几行简单的JavaScript就能搞定这个需求~咱们一步步来:

核心思路

首先让弹窗默认隐藏,然后通过JavaScript检测当前屏幕宽度:

  • 如果屏幕宽度小于你设定的阈值(比如768px,这是平板和手机的常见分界点,你可以自己改),就显示弹窗
  • 如果屏幕宽度大于等于阈值,就隐藏弹窗
  • 还要监听窗口大小变化,这样用户调整窗口尺寸时,弹窗能自动切换显示状态

完整代码实现

1. 修改后的HTML(给弹窗加个ID,方便JS定位)

<div class="alert" id="mobileAlert">
  <span class="closebtn" onclick="hideAlert()">&times;</span>
  Recommended to be used on PC or tablet.
</div>

2. 调整后的CSS(默认隐藏弹窗,优化叉号布局)

.alert {
  padding: 10px;
  background-color: #f44336; /* Red */
  color: white;
  margin-bottom: 15px;
  border-radius: 5px;
  display: none; /* 默认隐藏弹窗 */
}

.closebtn {
  margin-left: 15px;
  color: black;
  font-weight: bold;
  float: right;
  line-height: 15px;
  font-size: 20px;
  cursor: pointer;
  transition: 0.3s;
  background-color: white;
  border-radius: 20px;
  height: 13px;
  width: 13px;
  display: flex;
  align-items: center;
  justify-content: center; /* 让叉号在圆形背景里居中 */
}

.closebtn:hover {
  color: darkred;
}

3. 所需的JavaScript代码

// 获取弹窗元素
const mobileAlert = document.getElementById('mobileAlert');
// 设定屏幕宽度阈值(你可以改成自己想要的数值,比如600px)
const SCREEN_THRESHOLD = 768;

// 检测屏幕宽度并控制弹窗显示/隐藏的函数
function checkScreenSize() {
  const currentWidth = window.innerWidth;
  if (currentWidth < SCREEN_THRESHOLD) {
    mobileAlert.style.display = 'block';
  } else {
    mobileAlert.style.display = 'none';
  }
}

// 关闭弹窗的函数
function hideAlert() {
  mobileAlert.style.display = 'none';
}

// 页面加载完成后立即检测一次
window.addEventListener('load', checkScreenSize);
// 监听窗口大小变化,实时调整弹窗状态
window.addEventListener('resize', checkScreenSize);

额外小提示

  • 你可以随意修改SCREEN_THRESHOLD的值,比如改成600px,就是屏幕小于600px时触发弹窗
  • 如果想要用户关闭弹窗后,即使再缩小窗口也不再显示,可以加个localStorage记录状态,需要的话我再给你补充这部分代码~

备注:内容来源于stack exchange,提问作者Michael Borne VR -VRGamingAC-

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 15:19:08