手机端实现悬浮按钮,可拖动元素,并且具有惯性和边缘反弹效果
1:调用方法
<template>
<div id="sticky-btn">悬浮按钮</div>
</template>
<script>
import Inertia from '@/plugins/Inertia'
export default {
data() {},
mounted() {
new Inertia(document.getElementById('sticky-btn'))
}
}
</script>
<style lang="scss" scoped>
#sticky-btn {
width: 50px;
height: 50px;
border-radius: 50%;;
text-align: center;
background-color: #409EFF;
color: #fff;
padding: 5px;
font-size: 14px;
position: fixed;
top: 250px;
}
</style>
2:下面是Inertia.js 源码
/**
* @Inertia.js
* @description 拖动元素,并且具有惯性和边缘反弹效果
*/
(function (global, factory) {
if (typeof define === 'function' && (define.amd || define.cmd)) {
define(factory);
} else {
global.Inertia = factory();
}
}(this, function () {
'use strict';
var Inertia = function (ele, options) {
var defaults = {
// 是否吸附边缘
edge: true
};
var params = {};
options = options || {};
for (var key in defaults) {
if (typeof options[key] !== 'undefined') {
params[key] = options[key];
} else {
params[key] = defaults[key];
}
}
var data = {
distanceX: 0,
distanceY: 0
};
var win = window;
// 浏览器窗体尺寸
var winWidth = win.innerWidth;
var winHeight = win.innerHeight;
if (!ele) {
return;
}
// 设置transform坐标等方法
var fnTranslate = function (x, y) {
x = Math.round(1000 * x) / 1000;
y = Math.round(1000 * y) / 1000;
ele.style.webkitTransform = 'translate(' + [x + 'px', y + 'px'].join(',') + ')';
ele.style.transform = 'translate3d(' + [x + 'px', y + 'px'