通过 js 修改 css 变量来更简单的实现动画效果,dom.style.setProperty
的使用
setProperty
const a = document.querySelector('xx'); xx.style.setProperty(name, value);
|
顺带记一下获取的
getComputedStyle(a).getPropertyValue('--x');
|
demo
.iphoneText-wrap { margin: 100px auto; width: 400px; height: 400px; background-color: #000; overflow-y: auto; }
.text { height: 300%; }
.ihone-title { --x: 0%; position: sticky; top: 50%; transform: translateY(-50%); text-align: center; color: transparent; font-family: 'Bungee OutLine', cursive; background-image: linear-gradient(75deg, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 33.33%, rgba(255, 255, 255, 0) 66.67%, rgba(255, 255, 255, 0) 100%); background-position-x: calc(100% - var(--x)); -webkit-background-clip: text; background-size: 300% 100%; }
|
<section class="iphoneText-wrap"> <div class="text"> <h1 class="ihone-title">Less bezel, more screen.</h1> </div> </section>
|
const iphoneTextWrap = document.querySelector('.iphoneText-wrap'); const ipTitle = document.querySelector('.ihone-title');
iphoneTextWrap.addEventListener('scroll', () => { const x = iphoneTextWrap.scrollTop / (iphoneTextWrap.scrollHeight - iphoneTextWrap.clientHeight); ipTitle.style.setProperty('--x', `${x * 100}%`) })
|