求助:实现内容展示时切换图片灰度/彩色状态的功能
解决方案:点击按钮切换图片灰度/彩色状态
你的代码问题在于点击按钮时只修改了按钮自身的类,没有对目标图片进行操作,所以图片的灰度状态不会变化。以下是两种可行的修正方案:
方案1:通过类切换实现(推荐,易于维护)
修正后的CSS
body:not(.et-fb) .rv_element-do { display: none; } /* 单独定义灰度控制类 */ .grayscale { filter: grayscale(100%); } .rv_button_1-do{ background-color: blue; padding: 12px 20px; color: white; width: 200px; text-align: center; }
修正后的JS
jQuery(function($){ var revealButtons = { '.rv_button_1-do': '.rv_element_1-do' }; $.each(revealButtons, function(revealButton, revealElement) { $(revealButton).click(function(e){ e.preventDefault(); // 切换内容显示 $(revealElement).slideToggle(); // 切换图片的灰度类 $('.img-color').toggleClass('grayscale'); // 保留按钮自身的样式切换(如果需要) $(revealButton).toggleClass('rotateicon'); }); }); });
修正后的HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- 给图片添加默认灰度类 --> <img decoding="async" loading="lazy" src="https://media.npr.org/assets/img/2017/01/18/red-turtle_wide-03029731def2957b2fb69fb27e44c5c2e456f4a6-s800-c85.webp" width="80" height="165" alt="" class="img-color grayscale"> <p>Example text</p> <div class="rv_element-do rv_element_1-do"> <p>Helps to fund ten (10) Estuary pop-up outreach events, or one (1) water-quality testing location kit for an entire year, or a day of seagrass monitoring in the field. Included with this donation:</p> </div> <div class="rv_button_1-do"><a>button reveal</a></div>
方案2:直接修改CSS属性(无需新增类)
如果不想新增类,可以直接操作图片的filter属性:
修正后的JS
jQuery(function($){ var revealButtons = { '.rv_button_1-do': '.rv_element_1-do' }; $.each(revealButtons, function(revealButton, revealElement) { $(revealButton).click(function(e){ e.preventDefault(); $(revealElement).slideToggle(); // 直接切换图片的灰度滤镜 $('.img-color').css('filter', function(index, currentValue) { return currentValue === 'grayscale(100%)' ? 'grayscale(0%)' : 'grayscale(100%)'; }); $(revealButton).toggleClass('rotateicon'); }); }); });
对应CSS(无需修改,保留原样式)
body:not(.et-fb) .rv_element-do { display: none; } .img-color { filter: grayscale(100%); } .rv_button_1-do{ background-color: blue; padding: 12px 20px; color: white; width: 200px; text-align: center; }
对应HTML(无需修改)
保持你原有的HTML结构即可。
内容的提问来源于stack exchange,提问作者Giovanny
相关产品推荐
相关产品推荐

