鼠标悬停时同步影响左右相邻div元素的实现方案
实现悬停导航项时放大自身及左右相邻元素的效果
纯CSS方案(现代浏览器)
利用CSS的:has()伪类可以轻松实现需求,这是目前最简洁的纯CSS实现方式:
body { background-color: #D3D3D3; } .navbar { width: 600px; height: 50px; border-radius: 999px; background-color: white; padding: 5px; display: flex; align-items: center; justify-content: space-around; gap: 10px; /* 防止元素放大后重叠 */ } .navbar-item { border: 1px solid black; height: 50px; width: 50px; border-radius: 50%; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); /* 仿macOS平滑过渡 */ flex-shrink: 0; /* 避免flex容器压缩元素 */ } /* 当前悬停项放大20px */ .navbar-item:hover { width: 70px; height: 70px; } /* 右侧相邻元素放大10px */ .navbar-item:hover + .navbar-item { width: 60px; height: 60px; } /* 左侧相邻元素放大10px */ .navbar:has(.navbar-item:hover) .navbar-item:has(+ .navbar-item:hover) { width: 60px; height: 60px; }
HTML代码保持不变:
<div class="navbar"> <div class="navbar-item"></div> <div class="navbar-item"></div> <div class="navbar-item"></div> <div class="navbar-item"></div> <div class="navbar-item"></div> <div class="navbar-item"></div> <div class="navbar-item"></div> </div>
关键逻辑说明
- 右侧相邻元素:用你已经尝试过的
+相邻兄弟选择器直接选中悬停项的下一个元素。 - 左侧相邻元素:通过
:has()伪类实现反向选择:.navbar:has(.navbar-item:hover)检测父容器内存在被hover的导航项.navbar-item:has(+ .navbar-item:hover)选中"下一个兄弟是被hover元素"的当前元素,也就是hover项的左侧邻居
- 添加
transition和flex-shrink: 0让动画更流畅,避免布局跳动。
JavaScript兼容方案(支持旧浏览器)
如果需要兼容不支持:has()的旧浏览器,可以用JavaScript监听鼠标事件来控制元素样式:
const navbarItems = document.querySelectorAll('.navbar-item'); navbarItems.forEach(item => { item.addEventListener('mouseenter', () => { // 放大当前项 item.style.width = '70px'; item.style.height = '70px'; // 处理右侧相邻项 const next = item.nextElementSibling; if (next?.classList.contains('navbar-item')) { next.style.width = '60px'; next.style.height = '60px'; } // 处理左侧相邻项 const prev = item.previousElementSibling; if (prev?.classList.contains('navbar-item')) { prev.style.width = '60px'; prev.style.height = '60px'; } }); item.addEventListener('mouseleave', () => { // 恢复所有项的初始尺寸 navbarItems.forEach(el => { el.style.width = '50px'; el.style.height = '50px'; }); }); });
逻辑说明
- 监听每个导航项的
mouseenter事件,分别放大自身、左侧和右侧相邻元素 mouseleave事件触发时,将所有导航项恢复初始尺寸- 使用可选链操作符
?.简化边界判断,避免报错
内容的提问来源于stack exchange,提问作者user18353868
相关产品推荐
相关产品推荐

