介绍
语音播放的律动效果,通俗来说就是一个带动画的特殊样式的进度条,播放的部分带有上下律动的动画,未播放的部分是普通的灰色竖状条。
实现中夹带了less变量、继承和循环遍历,可以顺带学习一下。
结果展示
大致效果如图所示,样式需要改下,动画效果bar中的上边距调整下即可。
代码
<template> <div class="ripple-container"> <div class="blue-ripple"> <template v-for="(item, index) in rippleList"> <!-- if判断是判断当前进度来展示播放还是未播放 --> <div v-if="index >= Math.floor(rate * rippleList.length)" :key="index" :style="{ height: item + '%' }"></div> <span v-else :key="index"></span> </template> </div> </div> </template> <script> export default { props: { // 当前进度,传入0.4这种数字,进度需要从0逐渐增长,直接传入一个比较大的进度只会出现空白一段的现象 rate: { type: Number, default: 0.4, }, }, data() { return { rippleList: [ 40, 20, 40, 50, 70, 50, 20, 40, 30, 20, 30, 50, 100, 60, 20, 40, 30, 20, 30, 40, 70, 40, 20, 40, 40, 50, 70, 50, 20, 40, 30, 20, 30, 50, 100, 60, 20, ], }; }, }; </script> <style lang="less" scoped> .ripple-container { .blue-ripple { width: 100%; height: 48px; display: flex; // 纵向居中 align-items: center; // less变量,主题色 @color: #3370ff; // 给span标签增加样式,不设置高度是因为高度在动画中 // span标签用于展示波纹律动效果 span { width: 3px; border-radius: 18px; margin-right: 4px; } // div继承span标签的样式,用来统一波纹条样式 // div标签用于展示非正在播放的部分 div { // less继承需要将所有层级的类名都写上 &:extend(.ripple-container .blue-ripple span); background: rgba(0, 0, 0, 0.16); } @keyframes bar { 0% { background: @color; margin-top: 5%; height: 10%; } 50% { background: @color; margin-top: 0; height: 100%; } 100% { background: @color; margin-top: 5%; height: 10%; } } // less循环遍历生成span的样式 // 这里使用的是less的when语法,当@i小于等于@n时执行 .generate-span(@n,@i:1) when(@i <= @n) { span:nth-child(@{i}) { // 这个本来是想配合.generate-keyframes使用的,但是less似乎不支持遍历生成@keyframes的名字 // @name: ` "bar@{i}" `; animation: bar 2s 0.2s * @i infinite linear; } // 递归调用,生成下一个span的样式,这里when是判断是否结束的,这个递归调用用来形成遍历 .generate-span(@n, @i + 1); } // 循环遍历生成keyframes,生成有问题 .generate-keyframes(@n,@i:1) when(@i <= @n) { // 用less变量来解决不能直接使用@i问题 @keyfaramesName: ` "bar@{i}" `; // 似乎不支持动态生成keyframes的名称 @keyframes @keyfaramesName { 0% { background: @color; margin-top: 5%; height: 10; } 50% { background: @color; margin-top: 0; height: 100; } 100% { background: @color; margin-top: 5%; height: 10; } } .generate-keyframes(@n, @i + 1); } // 调用循环遍历 .generate-span(100); // .generate-keyframes(100); } } </style>
复制
结语
整体效果还可以,动态生成keyframes名称似乎不支持,如有大神了解,烦请指教。
对文章有好的建议,欢迎提出。讲解不细之处,欢迎指出。