Vue+TailwindCSS实现输入框动效
实现目标: 静态属性:输入框位于页面顶端、居中,圆角,框体内部为白色,1/5屏幕宽度,无外边框、框体阴影,闪烁光标为蓝色 动态属性:鼠标悬停时框体微微变大;聚焦后出现蓝色外边框,宽度增长且仍保持居中,框体阴影变为蓝色 其他:聚焦输入框时,背景逐渐模糊,取消聚焦后恢复 静态设计 HTML中的<input>标签可以承担基本的输入功能,创建文件SearchItem.vue,接下来使用TailwindCSS对默认输入框标签的样式进行调整 对于输入框位置与默认宽度的要求,可以使用网格布局,每行5列,而输入框位于第三列,这一布局设定应当在上层的文件中,而非SearchItem文件,所以这里先不对其进行设置 圆角、无外边框、框体阴影和蓝色光标可以使用rounded-xl、outline-none、shadow-xl、caret-blue-500来实现 考虑到后续会添加样式切换的动效,需要再加上transition-all以保证样式更改过程是平滑的 动态设计 TailwindCSS中,鼠标悬停的样式只需要使用hover:即可;获取焦点时的样式只需要使用focus: 悬停时框体变大:hover:scale-105 为了使悬停 -> 聚焦之后框体大小保持稳定,同时设置focus:scale-105 聚焦后出现蓝色外边框:focus:border-2、border-blue-500 宽度增长且仍居中,可以将元素左移的同时将宽度增加与之相同的长度:focus:-translate-x-40、focus:w-[40rem] 框体阴影变为蓝色:focus:shadow-blue-300/50 另外,可以设置转化的时长,这里设置400ms:duration-[400ms] 至此,对输入框的样式设计完成: <template> <input placeholder="搜索" class="shadow-xl duration-[400ms] hover:scale-105 focus:-translate-x-40 focus:w-[40rem] focus:border-2 focus:shadow-blue-300/50 focus:scale-105 border-blue-500 px-5 py-3 rounded-xl w-full transition-all outline-none caret-blue-500" name="search" type="search" /> </template> 上层结构 在上层文件中引入SearchItem.vue,然后设置网格布局并使这一模板位于5列中的第三列: <script setup lang="ts"> import searchItem from "./components/SearchItem.vue"; </script> <template> <div> <div class="grid grid-cols-5 gap-4 mt-2"> <searchItem class="col-start-3" /> </div> </div> </template> 效果如下: 为了使输入框能够输入内容,需要将输入的文字绑定至Vue中: <script setup lang="ts"> import { ref } from "vue"; defineOptions({ name: "searchItem", }); const input = ref(""); </script> <template> <input placeholder="搜索" class="shadow-xl duration-[400ms] hover:scale-105 focus:-translate-x-40 focus:w-[40rem] focus:border-2 focus:shadow-blue-300/50 focus:scale-105 border-blue-500 px-5 py-3 rounded-xl w-full transition-all outline-none caret-blue-500" name="search" type="search" v-model="input" /> </template> 背景模糊 接下来添加背景模糊 ...