JavaScript控制style.display无效疑似被CSS覆盖,求解决方案
问题解决:鼠标悬停切换GIF光标失效的问题
问题分析
你要实现的是鼠标进入左右区域时,分别显示对应的GIF光标,但如果在CSS里把#cursor div img设为display:none来隐藏初始状态,JS控制父div(prev--cursor/next--cursor)的display就会失效——因为JS改的是父元素的显示状态,但img本身被CSS强制隐藏了,父元素显示也没用。
解决方法
把初始隐藏的目标从img元素改成包含img的父div(#prev--cursor和#next--cursor),这样JS控制父div的display属性时,里面的img就能正常显示/隐藏,不会被CSS覆盖。
修改后的代码
HTML(无需改动)
<div id="cursor"> <div id="next--cursor"> <img src="https://media2.giphy.com/media/RgbTzGW9IIRHcUWxOJ/giphy.gif?cid=790b76114e5bfc8443de9eee9b628a5f3abf8c7781fb2c35&rid=giphy.gif&ct=s"> </div> <div id="prev--cursor"> <img src="https://media3.giphy.com/media/QvBKLx9rJwYhfvb5kE/giphy.gif?cid=790b761175a201200752f42876262319b308809adaf9f4eb&rid=giphy.gif&ct=s"> </div> </div> <div id="left"class="zone" data-hover="Prev"></div> <div id="right" class="zone" data-hover="next"></div>
CSS(调整初始隐藏目标)
/* 初始隐藏两个光标容器,img保持可见 */ #prev--cursor, #next--cursor { display: none; } #cursor div img { width:120px; height:auto; position:absolute; z-index:500; display:block; } /* 补充左右区域的样式,确保能触发鼠标事件 */ .zone { position: fixed; top: 0; bottom: 0; width: 50%; } #left { left: 0; } #right { right: 0; }
JavaScript(逻辑无需改动)
const cursor = document.querySelector("#cursor"); var prevgif = document.getElementById("prev--cursor"), nextgif = document.getElementById("next--cursor"), leftzone = document.getElementById("left"), rightzone = document.getElementById("right"); document.addEventListener("mousemove", function(event) { const x = event.pageX - 10; const y = event.pageY - 10; cursor.style.left = x + "px"; cursor.style.top = y + "px"; }); leftzone.addEventListener("mouseover", () => { prevgif.style.display = "block"; }) leftzone.addEventListener("mouseout", () => { prevgif.style.display = "none"; }); rightzone.addEventListener("mouseover", () => { nextgif.style.display = "block"; nextgif.style.opacity = "1"; }) rightzone.addEventListener("mouseout", () => { nextgif.style.display = "none"; });
额外说明
补充了.zone的基础样式,确保左右区域占据屏幕一半,能正常触发鼠标悬停事件(原代码缺失这部分,可能导致交互无响应)。JS控制父容器的显示状态,img始终保持可见,这样父容器显示时GIF就会正常加载显示,不会被CSS规则覆盖。
内容的提问来源于stack exchange,提问作者benimsson
相关产品推荐
相关产品推荐

