如何让折叠按钮与图片区域鼠标悬停高亮功能同时生效?
解决折叠按钮与图片悬停高亮共存问题
问题:折叠按钮与图片区域鼠标悬停高亮功能单独使用均正常,但一起使用时,折叠按钮展开后图片的悬停高亮失效。
原因分析
maphilight插件在页面加载时初始化,但此时图片所在的.content容器处于display:none状态,插件无法获取图片的正确尺寸与位置信息,导致后续展开后无法正常触发悬停高亮。
修改后的代码
完整代码
<!DOCTYPE html> <html> <head> <style> .collapsible { cursor: pointer; padding: 10px; border: none; text-align: left; outline: none; font-size: 15px; } .active, .collapsible:hover { background-color: #ccc; } .content { display: none; padding: 0 18px; overflow: hidden; } </style> </head> <body> <button type="button" class="collapsible"> <h1 id="Header">Collapsible header button</h1> </button> <div class="content"> <p>Map highlight test - Hover over the first 'o'-letter</p> <img src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" class="map" usemap="#simple"> <map name="simple"> <area href="#" shape="rect" coords="70,25,115,70" alt="Link" title="Test"> </map> </div> <script src="https://code.jquery.com/jquery-3.6.3.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/maphilight/1.4.2/jquery.maphilight.min.js"></script> <script> $(function() { // 初始隐藏状态下不初始化插件 }); var coll = document.getElementsByClassName("collapsible"); var i; for (i = 0; i < coll.length; i++) { coll[i].addEventListener("click", function() { this.classList.toggle("active"); var content = this.nextElementSibling; if (content.style.display === "block") { content.style.display = "none"; } else { content.style.display = "block"; // 内容展开后重新初始化maphilight $('.map').maphilight(); } }); } </script> </body> </html>
关键修改点
- 移除页面加载时的
maphilight初始化操作,改为在折叠按钮点击展开内容时,调用$('.map').maphilight()重新初始化插件。 - 确保图片容器可见后,插件能获取到正确的元素尺寸与位置信息,从而正常触发悬停高亮效果。
内容的提问来源于stack exchange,提问作者JanneI
相关产品推荐
相关产品推荐

