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

基于已设置的CSS媒体查询动态修改JS元素属性问题

解决方案:根据媒体查询动态调整下拉菜单位置

你当前的代码虽定义了window.matchMedia,但未利用其matches属性判断视口匹配状态,且滚动事件里的dropDown.style.top设置直接覆盖了媒体查询逻辑。同时,还需监听窗口大小变化,确保视口 resize 后样式同步更新。

以下是修改后的完整JS代码:

// 提前定义媒体查询实例,避免重复创建
const desktopMediaQuery = window.matchMedia('(min-width: 50em)');

// 绑定滚动事件与窗口 resize 事件
window.onscroll = scrollFunction;
window.addEventListener('resize', scrollFunction);

function scrollFunction() {
  const logo = document.getElementById("logo");
  const header = document.getElementById("header");
  const dropDown = document.getElementById("dropdownMenu");
  const isDesktop = desktopMediaQuery.matches;

  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    logo.style.width = '4em';
    header.style.background = '#000';
    // 根据视口类型设置下拉菜单top值
    dropDown.style.top = isDesktop ? '2.6em' : '0';
  } else {
    logo.style.width = '6em';
    header.style.background = '#0000009d';
    // 根据视口类型设置下拉菜单top值
    dropDown.style.top = isDesktop ? '4em' : '0';
  }

  // 移动端设置下拉菜单铺满视口
  if (!isDesktop) {
    dropDown.style.left = '0';
    dropDown.style.width = '100vw';
    dropDown.style.height = 'calc(100vh - 100%)'; // 可根据header实际高度调整计算值
  } else {
    // 桌面端重置样式,恢复常规下拉布局
    dropDown.style.left = '';
    dropDown.style.width = '';
    dropDown.style.height = '';
  }
}

关键改动说明:

  • 提前定义媒体查询实例,避免每次滚动重复创建,提升性能。
  • 添加resize事件监听,窗口大小变化时自动触发样式更新。
  • 在滚动逻辑的两个分支中,根据isDesktop状态动态设置dropDown.style.top。
  • 针对移动端额外设置left、width、height样式,实现下拉菜单铺满视口;桌面端重置这些样式,保持常规布局。

更优方案:CSS媒体查询+类名控制

优先推荐用CSS直接控制样式,仅通过JS切换类名,代码更简洁易维护:

CSS代码:

#dropdownMenu {
  /* 移动端默认样式 */
  top: 0;
  left: 0;
  width: 100vw;
  height: calc(100vh - var(--header-height)); /* 替换为header实际高度变量 */
}

@media (min-width: 50em) {
  #dropdownMenu {
    /* 桌面端样式 */
    top: 4em;
    left: auto;
    width: auto;
    height: auto;
  }
}

/* 滚动后的桌面端下拉菜单位置 */
.header-scrolled #dropdownMenu {
  top: 2.6em;
}

#header {
  background: #0000009d;
}

.header-scrolled {
  background: #000;
}

JS代码:

window.onscroll = scrollFunction;
window.addEventListener('resize', scrollFunction);

function scrollFunction() {
  const header = document.getElementById("header");
  const logo = document.getElementById("logo");
  
  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    header.classList.add('header-scrolled');
    logo.style.width = '4em';
  } else {
    header.classList.remove('header-scrolled');
    logo.style.width = '6em';
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 04:53:14