JS实现带有滚动效果的凸窗样式图像滑块

129 阅读1分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

前言

使用码上掘金查看效果

API

tranform-style

支持3D效果的CSS属性

逻辑

function drag(e){
  if (e.touches) e.clientX = e.touches[0].clientX;    

  gsap.to('.ring', {
    rotateY: '-=' +( (Math.round(e.clientX)-xPos)%360 ),
    onUpdate:()=>{ gsap.set('.img', { backgroundPosition:(i)=>getBgPos(i) }) }
  });
  
  xPos = Math.round(e.clientX);
}

function dragStart(e){ 
  if (e.touches) e.clientX = e.touches[0].clientX;
  xPos = Math.round(e.clientX);
  gsap.set('.ring', {cursor:'grabbing'})
  $(window).on('mousemove touchmove', drag);
}

$(window).on('mousedown touchstart', dragStart);

PC端按钮按下和移动端触摸开始执行的逻辑

  • 更改鼠标的样式从grab变为grabbing
  • 更改rotationY

drag函数处理鼠标拖动的样式变化

设置.ring的Y轴旋转角度,根据i动态计算,backgroundPosition的位置

Timeline

时间线动画,页面初始化执行

sap.timeline()
    .set('.ring', { rotationY:180, cursor:'grab' }) //set initial rotationY so the parallax jump happens off screen
    .set('.img',  { // apply transform rotations to each image
      rotateY: (i)=> i*-36,
      transformOrigin: '50% 50% 500px',
      z: -500,
      // backgroundImage:(i)=> 'url(https://picsum.photos/id/'+(i+32)+'/600/400/)',
      backgroundImage:(i)=> `url(${imgs[i]})`,
      backgroundPosition:(i)=>getBgPos(i),
      backfaceVisibility:'hidden'
    })    
    .from('.img', {
      duration:1.5,
      y:200,
      opacity:0,
      stagger:0.1,
      ease:'expo'
    })
    .add(()=>{
      $('.img').on('mouseenter', (e)=>{
        let current = e.currentTarget;
        gsap.to('.img', {opacity:(i,t)=>(t==current)? 1:0.5, ease:'power3'})
      })
      $('.img').on('mouseleave', (e)=>{
        gsap.to('.img', {opacity:1, ease:'power2.inOut'})
      })
    }, '-=0.5')
  1. 设置.ringY轴旋转180,cursor样式为grab
  2. 设施.imgY轴旋转角度根据i,背景图片,backgroundPosition根据i计算,backfaceVisibility设置为hidden
  3. from设置初始化动画的起点css元素
  4. 添加回调动画,给img类元素添加mouseenter和mouseleave的样式变化动画

总价

主要逻辑是3D效果的变化,在日常大家很少使用到的属性