如何在鼠标移入Vimeo嵌入iframe时隐藏SVG自定义光标?
解决自定义SVG光标在Vimeo iframe边缘卡顿及进出隐藏/恢复问题
问题分析
你的自定义SVG光标在页面滚动和普通区域表现正常,但在Vimeo嵌入的iframe边缘出现卡顿,且现有代码无法实现「鼠标进入iframe隐藏光标、离开时恢复」的需求,核心问题在于:
- DOM元素未完全加载就执行事件绑定,导致iframe获取失败
- 原生JS的
mouseover/mouseleave对跨域iframe的事件捕获存在兼容性问题 - 未正确引用自定义光标元素,且
display: none/block的切换方式易引发视觉卡顿
调整方案
修改JS的最后部分,同时优化事件绑定逻辑,具体调整如下:
- 确保DOM加载完成后执行代码:将iframe的事件绑定逻辑包裹在
$(document).ready()中,避免iframe元素未加载时获取失败 - 统一使用jQuery操作元素:避免原生JS与jQuery混用导致的变量引用问题
- 用
mouseenter/mouseleave替代mouseover/mouseleave:减少事件冒泡带来的误触发,提升边缘区域的响应灵敏度 - 用
opacity过渡替代display切换:实现平滑的显示/隐藏效果,避免卡顿感
修改后的完整JS代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> let lastX, lastY, lastScrolled = 0; $(document).on('mousemove', function(e) { lastX = e.pageX - 1; lastY = e.pageY - 1; $('#cursor').css({ left: e.pageX - 1, top: e.pageY - 1, pointerEvents: 'none' }); }); $(window).scroll(function(event) { if (lastScrolled != $(window).scrollTop()) { lastY -= lastScrolled; lastScrolled = $(window).scrollTop(); lastY += lastScrolled; } $('#cursor').css({ left: lastX, top: lastY, pointerEvents: 'none' }); }); // 调整后的iframe事件绑定逻辑 $(document).ready(function() { const $cursor = $('#cursor'); $('iframe').on('mouseenter', function() { $cursor.css('opacity', '0'); }).on('mouseleave', function() { $cursor.css('opacity', '1'); }); }); </script>
配套CSS优化(可选)
为了让光标显示/隐藏的过渡更平滑,给#cursor添加过渡属性:
#cursor { display: block; position: absolute; z-index: 9999; pointer-events:none; width: 1.2rem; height: auto; transition: opacity 0.1s ease; /* 添加过渡效果 */ }
完整代码示例
HTML
<svg version="1.1" id="cursor" style="width:1.2rem;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 30 38" enable-background="new 0 0 30 38" xml:space="preserve"> <polygon class="cursorshape" points="29.397,31.059 29.397,28.54 29.397,24.939 29.397,22.42 29.397,18.819 29.397,16.3 29.397,10.18 0.603,0.822 0.603,6.942 0.603,9.46 0.603,13.062 0.603,15.581 0.603,19.181 0.603,21.701 0.603,27.82 29.397,37.178 "/> </svg> <div style="width:50%"> <div class="embedvid ratio-16-9"> <iframe src='https://player.vimeo.com/video/766323945' frameborder='0' webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> </div> </div>
CSS
body,html { cursor: none !important; } #cursor { display: block; position: absolute; z-index: 9999; pointer-events:none; width: 1.2rem; height: auto; transition: opacity 0.1s ease; } @media only screen and (max-width: 960px) { * { cursor: default !important; } #cursor{display: none;} } #cursor .cursorshape {fill: #d9e021;} .embedvid {position: relative; height: 0; overflow: hidden; max-width: 100%;} .embedvid iframe, .embedvid object, .embedvid embed {position: absolute; top: 0; left: 0; width: 100%; height: 100%;} .ratio-16-9 {padding-bottom: 56.25%;}
内容的提问来源于stack exchange,提问作者user3106225
相关产品推荐
相关产品推荐

