当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue 让元素抖动/摆动起来的实现代码

Vue 让元素抖动/摆动起来的实现代码

2018年08月08日  | 移动技术网IT编程  | 我要评论

wwe2015最新赛事,的哥解救被困男子,星无火

首先展示一下效果,狠狠点击

代码github : https://github.com/zhangkunusergit/vue-component

先说一下用法:

<jitter :start.sync="抖动控制器" :range="{ 包含x,y, z }" :shift-percent="0.1">
 这里是你要抖动的元素
</jitter>

思路:

1.抖动就是摆动,现实中的钟摆可以很形象。

2.当摆动到临界点后,就会向相反的方向摆动。

3.在没有动力时,摆动会慢慢停止。

初始化抖动:

/**
 * 初始化抖动
 */
initjitter() {
 // 把start变成false, 方便下次点击
 this.$emit('update:start', false);
 // 清除上次动画
 this.clearanimate();
 // 设置currentrange, 填充this.range 中没有的项
 this.currentrange = object.assign({}, { x: 0, y: 0, z: 0 }, this.range);
 // 获取需要操作的的项 和 每次需要摆动的量
 const { position, shiftnumber } = this.getpositionandshiftnumber();
 this.position = position;
 this.shiftnumber = shiftnumber;
 // 初始 move 起始点是0
 this.move = { x: 0, y: 0, z: 0 };
 // 初始时 是顺时针
 this.isclockwise = true;
 // 执行动画
 this.timer = window.requestanimationframe(this.continuejitter);
},

这里准备动画开始前的工作。

执行动画:

// 持续抖动
continuejitter() {
 this.refreshmove(this.isclockwise ? -1 : 1);
 // 绝对值
 const absmove = this.getabsmove();
 const currentrange = this.currentrange;
 let changedirection = false;
 for (let i = 0, l = this.position.length, p; i < l; i += 1) {
 p = this.position[i];
 // 判断是否到达临界值,到达后 应该反方向执行动画
 if (currentrange[p] <= absmove[p]) {
  // 等比例缩减
  this.currentrange[p] -= this.shiftnumber[p];
  // 判断如果已经无力再摆动,就让摆动停止, 只要有一个值达到了0,所有都会达到
  if (this.currentrange[p] <= 0) {
  // 停止在起始点上
  this.jitterview({ x: 0, y: 0, z: 0 });
  // 清除动画
  this.clearanimate();
  return;
  }
  // 更新move为临界点
  this.move[p] = this.isclockwise ? -this.currentrange[p] : this.currentrange[p];
  // 改变摆动方向
  changedirection = true;
 }
 }
 if (changedirection) {
 // 摆动方向取反
 this.isclockwise = !this.isclockwise;
 }
 // 更新元素位置
 this.jitterview(this.move);
 // 继续执行动画
 this.timer = window.requestanimationframe(this.continuejitter);
},

执行动画,当判断已经无力摆动后,让元素回归到原来的位置,并清除动画。

修改元素位置:

/**
 * 修改元素位置
 * @param x
 * @param y
 * @param z
 */
jitterview({ x = 0, y = 0, z = 0 }) {
 this.$el.style.transform = `translate3d(${x}px, ${y}px, ${z}px)`;
},

这里需要判断需要 z 轴摆动吗? 当需要时,必须给当前元素的父级添加 perspective, 从而修改子级透视效果

mounted() {
 // 如果要执行 z 轴动画需要设置父级,从而修改子级透视效果,否则 z 轴没有效果
 if (this.range.z > 0) {
 const parentel = this.$el.parentnode;
 object.keys(this.perspectivestyle).foreach((key) => {
  parentel.style[key] = this.perspectivestyle[key];
 });
 }
},

最后看看可以传的属性:

props: {
 // 抖动范围,单位是px, 例如:{x: 4, y: 2, z: 10}
 range: {
 type: object,
 default: () => { return { z: 8 }; },
 },
 start: {
 type: boolean,
 required: true,
 },
 shiftpercent: {
 type: number,
 default: 0.1, // 移动range中初始值的百分比
 },
 perspectivestyle: {
 type: object,
 default: () => {
  return {
  perspective: '300px',
  perspectiveorigin: 'center center'
  };
 }
 }
},

上面是可以传的属性,大家可以按照情况修改

最后:

这里我只写了简单的动画,也可以根据不同情况进行修改,从而达到想要的效果。这里已经满足输入框错误抖动的效果了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网