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

如何实现Div鼠标悬停展开时不移动其他Div而是覆盖相邻元素

解决方案

要实现鼠标悬停时Div展开并覆盖相邻元素、不移动其他Div的效果,可通过调整CSS定位属性并配合原有JavaScript逻辑实现,修改后的完整代码如下:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8" />
    <style>
        .wrap{
            font-size: 160px;
            font-weight: bold;
            height: 450px;
            width: 1100px;
            display: flex;
            flex-direction: row;
            align-items: center;
            border-style: solid;
            border-width: 1px;
            position: relative; /* 为子元素相对定位提供参考 */
        }
        .a, .b, .c, .d, .e{ /* 合并选择器简化代码 */
            width: 220px;
            height: 350px;
            border-style: solid;
            border-width: 1px;
            position: relative; /* 允许元素覆盖相邻元素 */
            flex-shrink: 0; /* 禁止元素被压缩,保持原有宽度 */
            z-index: 1; /* 默认层级 */
        }
    </style>
    <script type="application/javascript">
        function enlarge(id){
            var element = document.getElementById(id);
            element.style.height = "440px";
            element.style.width = "260px";
            element.style.borderWidth = "1px";
            element.style.borderStyle = "solid";
            element.style.zIndex = "2"; /* 提升层级,确保覆盖其他元素 */
        }
        function reduce(id){
            var element = document.getElementById(id);
            element.style.height = "350px";
            element.style.width = "220px";
            element.style.borderWidth = "1px";
            element.style.borderStyle = "solid";
            element.style.zIndex = "1"; /* 恢复默认层级 */
        }
    </script>
</head>
<body>  
    <center>
        <div class="wrap">
            <div class="a" id="a" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">A</div>
            <div class="b" id="b" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">B</div>
            <div class="c" id="c" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">C</div>
            <div class="d" id="d" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">D</div>
            <div class="e" id="e" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">E</div>
        </div>
    </center>
</body>
</html>

关键修改说明

  • 父容器.wrap添加position: relative:为子元素的相对定位提供坐标参考,确保子元素的覆盖范围在容器内。
  • 子元素统一设置flex-shrink: 0:阻止Flex布局下子元素因空间变化被压缩,保证其他Div始终保持原有尺寸不移动。
  • 子元素添加position: relative与默认z-index:1:允许元素在不脱离文档流的情况下扩展尺寸,默认层级一致不会互相覆盖。
  • JavaScript函数中调整z-index:悬停时将当前Div层级设为2,确保它覆盖在其他Div上方;离开时恢复层级,避免影响后续交互。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:37