项目中如果图片比较多的话,或者数据是请求过来的,为了用户有更好的开发体验,就会设置一个固定的盒子占着位,这个我印象特别深的就是知乎。
因为项目是用ts写的,所以粘贴的还是ts代码,为了用户看着舒服一点,在骨架屏上添加了一些动画,看起来交互效果好一点,然后在项目中把下面的代码复制上去,按照样式进行一定的修改即可。骨架的大小样式不同,组件使用的就是组件传值的方式进行的样式调整。
注意:
透明度是可以继承的,所以对父盒子设置透明度一样作用在孩子身上。
<script lang="ts" setup name="XtxSkeleton">
defineProps({
bg: {
type: String,
default: '#efefef',
},
width: {
type: Number,
required: true,
},
height: {
type: Number,
required: true,
},
animated: {
type: Boolean,
default: false,
},
fade: {
type: Boolean,
default: false,
},
})
</script>
<template>
<div class="xtx-skeleton" :style="{ width: width + 'px', height: height + 'px' }" :class="{ shan: animated, fade: fade }">
<div class="block" :style="{ backgroundColor: bg }"></div>
</div>
</template>
<style scoped lang="less">
.xtx-skeleton {
display: inline-block;
position: relative;
overflow: hidden;
vertical-align: middle;
.block {
width: 100%;
height: 100%;
border-radius: 2px;
}
}
.shan {
&::after {
content: '';
position: absolute;
animation: shan 1.5s ease 0s infinite;
top: 0;
width: 50%;
height: 100%;
background: linear-gradient(to left, rgba(255, 255, 255, 0) 0, rgba(255, 255, 255, 0.3) 50%, rgba(255, 255, 255, 0) 100%);
transform: skewX(-45deg);
}
}
@keyframes shan {
0% {
left: -100%;
}
100% {
left: 120%;
}
}
.fade {
animation: fade 1s linear infinite alternate;
}
@keyframes fade {
from {
opacity: 0.2;
}
to {
opacity: 1;
}
}
</style>