input中有2个属性,一个是focus获取焦点,一个是blur失去焦点。获取焦点就是我们点击输入框时输入框被选中;失去焦点即点击输入框以外的区域,今天就用这两种属性做一个点击输入框的动画效果。
先写个输入框,代码如下:
<template><view class="out"><input type="text" :value="iptvalue"></view>
</template><script setup>
import {ref} from "vue" ;
const iptvalue = ref("") ;
</script><style lang="scss" scoped>.out{padding: 0 20px;margin-top: 40px;input{border: 1px solid #ccc;height: 40px;}} </style>
效果如下:
接下来,把focus和blur属性加入进去,无论是focus还是blur都是会有一个value返回值的,等会我们看控制台,先放上代码:
<template><view class="out"><input type="text" :value="iptvalue" @focus="onfocus" @blur="onblur"></view>
</template><script setup>
import {ref} from "vue" ;
const iptvalue = ref("") ;
function onfocus(e){console.log(e);
}
function onblur(e){console.log(e);
}
</script><style lang="scss" scoped>.out{padding: 0 20px;margin-top: 40px;input{border: 1px solid #ccc;height: 40px;}} </style>
注意看控制台,不管是focus还是blur,都会有返回值,这个返回值是可以用来作运算的,不过今天不会说到运算,只是根据返回值做一个点击输入框后的动画效果:
接下来,插入动画的小图片,并为其设置好CSS样式,代码如下:
<template><view class="out"><input type="text" :value="iptvalue" @focus="onfocus" @blur="onblur"><image src="../../static/chicken.gif" class="pic"></image></view>
</template><script setup>
import {ref} from "vue" ;
const iptvalue = ref("") ;
function onfocus(e){console.log(e);
}
function onblur(e){console.log(e);
}
</script><style lang="scss" scoped>.out{padding: 0 20px;margin-top: 40px;position: relative;input{border: 1px solid #ccc;height: 40px;position: relative;z-index: 2;background: #fff;}.pic{width: 24px;height: 24px;z-index: 1;position: absolute;top: -24px;left: calc(50% - 12px);}} </style>
效果如下:
加入逻辑部分,代码如下:
<template><view class="out"><input type="text" :value="iptvalue" @focus="isActive = true" @blur="isActive = false"><image src="../../static/chicken.gif" class="pic":class = "isActive?'active':''"></image></view>
</template><script setup>
import {ref} from "vue" ;
const iptvalue = ref("") ;
const isActive = ref(false) ;
/*
function onfocus(e){isActive.value = true ;
}
function onblur(e){isActive.value = false ;
}
*/
</script><style lang="scss" scoped>.out{padding: 0 20px;margin-top: 40px;position: relative;input{border: 1px solid #ccc;height: 40px;position: relative;z-index: 2;background: #fff;}.pic{width: 24px;height: 24px;z-index: 1;position: absolute;top: 0px;left: calc(50% - 12px);transition: top 0.3s;}.pic.active{top: -24px;}} </style>
最终效果: