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

可滚动垂直菜单hover显示子菜单溢出,如何实现子菜单底部锁定不超屏

功能实现方案

1. 基础CSS调整

修改原有CSS规则,增加外层容器定位属性、子菜单溢出滚动规则:

/* 外层菜单容器新增规则,作为子菜单的定位基准 */
.dd_menu {
  position: relative;
  max-height: 100vh;
  overflow-y: auto;
}

.nav-drop {
    position: absolute;
    /* 删除原有固定top:0规则,改为JS动态赋值 */
    left: 100%;
    width: 100%;
    background: #fff;
    display: none;
    text-align: center;
    padding: 20px 0;
    overflow-y: auto; /* 子菜单内容超出高度限制时内部滚动 */
}

.dd_menu ul li a.dd_menu_a.active + .nav-drop{
    display: block;
}

2. 交互逻辑优化

修改JS代码,悬浮时动态计算子菜单的偏移位置和最大允许高度,保证底部对齐屏幕下边缘:

var dd_menu_a = document.querySelectorAll(".dd_menu_a");
const menuWrapper = document.querySelector('.dd_menu');
const viewportHeight = window.innerHeight;

dd_menu_a.forEach(function(dd_menu_item){
    dd_menu_item.addEventListener("mouseover", function(){
        dd_menu_a.forEach(function(dd_menu_item){
            jQuery(".nav-main__brands__items").removeClass("active");
            dd_menu_item.classList.remove("active");
        })
        dd_menu_item.classList.add("active");
        
        // 新增子菜单位置计算逻辑
        const currentNavDrop = dd_menu_item.nextElementSibling;
        if(!currentNavDrop || !currentNavDrop.classList.contains('nav-drop')) return;
        // 计算元素相对位置
        const itemRect = dd_menu_item.getBoundingClientRect();
        const wrapperRect = menuWrapper.getBoundingClientRect();
        const dropTop = itemRect.top - wrapperRect.top;
        const maxDropHeight = viewportHeight - itemRect.top;
        // 给子菜单赋值样式
        currentNavDrop.style.top = dropTop + 'px';
        currentNavDrop.style.maxHeight = maxDropHeight + 'px';
    })
})

如果存在边框、边距偏移,可在maxDropHeight计算时减去对应数值做微调即可。


内容的提问来源于stack exchange,提问作者ΝΙΚΟΛΑΟΣ ΚΟΥΚΗΣ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:06:02