CSS图片按钮Hover黑白转彩色效果不生效问题求助
问题排查与修复方案
核心问题1:CSS hover选择器语法错误
你编写的hover规则中,选择器和:hover之间多了空格:
/* 错误写法,空格代表选中该元素的子元素的hover状态 */ #fb-button :hover{} #gl-button :hover{}
空格在CSS选择器中属于后代选择器,上述写法含义是选中#fb-button内部所有子元素的hover状态,而非按钮元素本身的hover状态,因此交互样式无法触发。
将空格删除即可解决:
/* 正确写法,选中元素自身的hover状态 */ #fb-button:hover{} #gl-button:hover{}
核心问题2:HTML ID属性重复冲突
你的HTML代码中,外层div和内层button都使用了相同的id值:
<div id="fb-button"> <div class="et_pb_code_inner"> <button id="fb-button" onclick="myFbFunction()"></button> </div> </div>
同一个页面内ID必须是唯一值,重复ID会导致CSS样式匹配、JS元素获取逻辑异常,建议修改外层div的ID为不重复的命名,例如:
<div id="fb-button-wrapper"> <div class="et_pb_code_inner"> <button id="fb-button" onclick="myFbFunction()"></button> </div> </div>
可选优化建议
你当前使用的背景图地址是http协议,你的站点是https协议,部分浏览器会拦截混合内容导致图片加载失败,建议将背景图URL改为https开头。
修改后的完整参考代码
CSS代码:
#fb-button { background-image: url('https://gxm.ece.myftpupload.com/wp-content/uploads/2021/10/18-181292_facebook-5-star-reviews-hd-png-download__1_-removebg-preview.png'); width: 480px; height: 200px; border: none; background-color: transparent; background-size: cover; background-position: center center; cursor: pointer; -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: grayscale(100%); transition: all 300ms ease; } #fb-button:hover{ -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); -ms-filter: grayscale(0%); -o-filter: grayscale(0%); filter: grayscale(0%); width: 485px; height: 205px; } #gl-button { background-image: url('https://gxm.ece.myftpupload.com/wp-content/uploads/2021/10/download__3_-removebg-preview.png'); width: 480px; height: 200px; border: none; background-color: transparent; background-size: cover; background-position: center center; cursor: pointer; -webkit-filter: grayscale(100%); -moz-filter: grayscale(100%); -ms-filter: grayscale(100%); -o-filter: grayscale(100%); filter: grayscale(100%); transition: all 300ms ease; } #gl-button:hover{ -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); -ms-filter: grayscale(0%); -o-filter: grayscale(0%); filter: grayscale(0%); width: 485px; height: 205px; } #fb-review, #gl-review { display: none; }
HTML代码:
<div id="fb-button-wrapper"> <div class="et_pb_code_inner"> <button id="fb-button" onclick="myFbFunction()"></button> </div> </div> <div id="fb-review" class="et_pb_module"> <div class="et_pb_code_inner"> <!-- this is the fb review source code for the review template --> <script src="https://apps.elfsight.com/p/platform.js" defer></script> <div class="elfsight-app-f24ab324-722d-40af-b413-b052f62fdc99"></div> <script> function myFbFunction() { var x = document.getElementById('fb-review'); x.style.display = x.style.display === 'block' ? 'none' : 'block'; } </script> </div> </div>
内容的提问来源于stack exchange,提问作者Shohan
相关产品推荐
相关产品推荐

