跟随鼠标的div元素(JS)悬停CSS关键帧动画时消失,如何修复?
问题:鼠标跟随小球在悬停抖动图片时消失的解决办法?
我通过JS的mousemove事件实现了一个包裹小球图片的div跟随鼠标移动,同时还有另一个独立div中的图片,在鼠标悬停时会通过CSS关键帧动画实现抖动效果。
问题在于,当我悬停到这个抖动图片上时,跟随鼠标的小球图片会消失。请问有没有办法在抖动图片处于动画状态时,让跟随鼠标的小球图片始终显示在其上方?
现有代码
CSS代码
body { background-color: white; } h1 { color: teal; font-family: Arial, Helvetica, sans-serif; text-align: center; } div { background-color: teal; padding: 5%; text-align: center; } #circle { max-width: 10%; background-color: transparent; position: absolute; } #circle:hover { cursor: url('***********'), auto; } #shakingimage { max-width: 45%; position: relative; } #shakingimage:hover { /* Start the shake animation and make the animation last for 0.5 seconds */ animation: shake 0.5s; /* When the animation is finished, start again */ animation-iteration-count: infinite; cursor: url('************'), auto; } @keyframes shake { 0% { transform: translate(1px, 1px) rotate(0deg); } 10% { transform: translate(-1px, -2px) rotate(-1deg); } 20% { transform: translate(-3px, 0px) rotate(1deg); } 30% { transform: translate(3px, 2px) rotate(0deg); } 40% { transform: translate(1px, -1px) rotate(1deg); } 50% { transform: translate(-1px, 2px) rotate(-1deg); } 60% { transform: translate(-3px, 1px) rotate(0deg); } 70% { transform: translate(3px, 1px) rotate(-1deg); } 80% { transform: translate(-1px, -1px) rotate(1deg); } 90% { transform: translate(1px, 2px) rotate(0deg); } 100% { transform: translate(1px, -2px) rotate(-1deg); } } .buttonbox { display: inline-flex; justify-content: center; flex-direction: row; } button { padding: 15px 25px; margin: 5px; font-size: 24px; text-align: center; cursor: pointer; outline: solid 2px white; color: #ffffff; background-color: #008080; border: none; border-radius: 15px; box-shadow: 0 9px #999; } button:hover { background-color: rgb(0, 172, 172); } button:active { background-color: #008080; box-shadow: 0 5px #666; transform: translateY(4px); }
JavaScript代码
let circle = document.getElementById('circle') const onMouseMove = (e) => { circle.style.left = e.pageX + 'px' circle.style.top = e.pageY + 'px' } document.addEventListener('mousemove', onMouseMove)
解决方案
问题的核心是元素堆叠层级冲突:抖动图片设置了position: relative,跟随鼠标的小球是position: absolute。默认情况下,relative定位元素的堆叠层级会高于未设置z-index的absolute元素,鼠标悬停触发抖动动画时,抖动图片就会覆盖住小球。
只需要给小球容器#circle添加一个足够高的z-index值,就能让它始终处于最上层:
#circle { max-width: 10%; background-color: transparent; position: absolute; z-index: 9999; /* 添加这一行 */ }
如果后续抖动图片设置了更高的z-index,只要保证小球的z-index数值比它大即可,9999是一个常用的足够大的数值,基本不会和其他元素的层级冲突。
内容的提问来源于stack exchange,提问作者Hannah Burgoyne
相关产品推荐
相关产品推荐

