如何通过单JS脚本实现桌面与移动端头部图片缩放效果适配
方案1:CSS媒体查询+适配版JS(最推荐,性能最优,适配GeneratePress无额外配置)
完整CSS代码
/* 公共样式,桌面移动端通用 */ .page-hero { transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important; opacity: 0; } /* 桌面端样式,断点768px可根据自己的需求调整 */ @media (min-width: 768px) { .page-hero { background-size: 150% auto; } } /* 移动端样式 */ @media (max-width: 767.98px) { .page-hero { background-size: 300% auto; } }
完整JS代码
<script> const pagehero = document.querySelector('.page-hero'); // 768px为移动端/桌面端分界,和CSS断点保持一致即可 const MOBILE_BREAKPOINT = 768; function hero_animation(){ if(!pagehero) return; // 兼容无hero区域的页面,避免报错 const finalBgSize = window.innerWidth >= MOBILE_BREAKPOINT ? '100%' : '200%'; pagehero.style.backgroundSize = finalBgSize; pagehero.style.opacity = '1'; } window.onload = hero_animation; // 如果需要支持横竖屏切换后重新适配,可取消注释下方代码 // window.addEventListener('resize', hero_animation); </script>
GeneratePress适配操作
把上述CSS粘贴到「外观」-「自定义」-「额外CSS」中,JS代码粘贴到你已创建的Hero Elements的代码区域,或者新建一个WP_Footer钩子类型的Elements,设置全站生效即可。
方案2:纯JS全动态适配(适合需要更多自定义逻辑的场景)
如果不想拆分CSS,也可以用JS直接判断屏幕宽度动态设置初始样式和最终样式,代码如下:
<script> const pagehero = document.querySelector('.page-hero'); const MOBILE_BREAKPOINT = 768; function setHeroInitStyle() { if(!pagehero) return; const initBgSize = window.innerWidth >= MOBILE_BREAKPOINT ? '150% auto' : '300% auto'; pagehero.style.cssText += ` transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important; opacity: 0; background-size: ${initBgSize}; `; } function hero_animation(){ if(!pagehero) return; const finalBgSize = window.innerWidth >= MOBILE_BREAKPOINT ? '100%' : '200%'; pagehero.style.backgroundSize = finalBgSize; pagehero.style.opacity = '1'; } // 先设置初始样式,加载完成后执行动画 setHeroInitStyle(); window.onload = hero_animation; </script>
这个方案不需要额外加CSS,直接把整段JS放到Elements中即可生效。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

