Skip to content

FLIP

  • FLIP就是First、Last、Invert、Play。

First

表示转换元素的初始状态。

Last

表示转换元素的最终状态。

Invert

通过transform反转First和Last之间的变化。例如First在向下移动90px得到Last,就将Last在向上移动90px,让它看起来像First。

Play

将Invert的变化删除,让Last回到原来的位置。

示例代码

js
class Flip {
    constructor(element, options = null) {
        this.element = element;
        // 记录First状态
        this.first = element.getBoundingClientRect();
        this.options = options ? options : {
            duration: 500,
            easing: 'ease-in-out'
        };
    }
    // 更新First
    updateFirst(){
        this.first = this.element.getBoundingClientRect();
    }

    // 播放动画
    play(options=null){
        // 当改变element样式时,调用play,记录Last状态
        let last = this.element.getBoundingClientRect();
        // 变化的值,这里用first和last的差值(因为要将Last变化到First)
        let delta = {
            x: this.first.x - last.x,
            y: this.first.y - last.y,
            width: this.first.width / last.width,
            height: this.first.height / last.height
        };
        let player = this.element.animate([
            // 将Last变化到First
            {
                transformOrigin: 'top left',
                transform: `
                translate(${delta.x}px, ${delta.y}px) 
                scale(${delta.width}, ${delta.height})`
            },
            // 清除变化
            {
                transformOrigin: 'top left',
                transform: 'none'
            }
        ], options ? options : this.options);
        player.onfinish = () => {
            this.updateFirst();
        };
    }
}

示例

html
<div style="width: 100px; height: 100px;">
    <div ref="box1" class="technology-flip-box1" @click="box1Click"></div>
</div>
css
.technology-flip-box1{
    position: relative;
    width: 100px;
    height: 100px;
    background-color: pink;
    z-index: 99;
    transition: background-color 0.5s ease-in-out, opacity 0.5s ease-in-out;
}
.technology-flip-box1-to{
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: #66c2f8;
    opacity: 0.5;
}
javascript
const box1 = ref(null);
let flip;

onMounted(() => {
    flip = new Flip(box1.value);
    
})
function box1Click(){
    flip.updateFirst();
    if(box1.value.classList.contains('technology-flip-box1-to')){
        box1.value.classList.remove('technology-flip-box1-to');
    }else{
        box1.value.classList.add('technology-flip-box1-to');
    }
    flip.play();
}