js封装随意拖动的悬浮按钮

原生js直接搞定,不依赖插件,话不多说直接上代码

var drag = new Object();
	drag = {
		opts: function(opt){
			var opts = {
				warp: '', //--可选参数,父容器
			}
			return $.extend(opts, opt, true);
		},
		on: function(opt, callback){ //创建
			var _this = this;
			var _opts = _this.opts(opt);
			var oL,oT,oLeft,oTop;
			var ui = {
				warp: document.querySelector('body'),
				main: _opts.warp,
				currentHeight: _opts.warp.offsetHeight,
				maxW: window.screen.width - _opts.warp.offsetWidth,
				maxH: window.screen.height - _opts.warp.offsetHeight
			}
			ui.main.addEventListener('touchstart', function(e) {
				var ev = e || window.event;
				var touch = ev.targetTouches[0];
				oL = touch.clientX - ui.main.offsetLeft;
				oT = touch.clientY - ui.main.offsetTop;
				window.addEventListener("touchmove", preventDefault, { passive: false });
			})
			ui.main.addEventListener('touchmove', function(e) {
				var _self = this;
				var ev = e || window.event;
				var touch = ev.targetTouches[0];
				oLeft = touch.clientX - oL;
				oTop = touch.clientY - oT;
				oLeft < 0 ? oLeft = 0 : oLeft >= ui.maxW ? oLeft = ui.maxW : '';
				oTop < 0 ? oTop = 0 : oTop >= ui.maxH ? oTop = ui.maxH : '';
				ui.main.style.left = oLeft + 'px';
				ui.main.style.top = oTop + 'px';
				typeof callback == "function" ?  callback({el: _self, type: 'touchmove'}) : '';
			})
			ui.main.addEventListener('touchend', function() {
				var _self = this;
				oLeft > 0 && oLeft < ui.maxW / 2 ? oLeft = 0 : oLeft > ui.maxW / 2 && oLeft < ui.maxW ? oLeft = ui.maxW : '';
				ui.main.style.left = oLeft + 'px';
				ui.main.style.transition = 'left .3s';
				var timer = setTimeout(function(){
					ui.main.style.transition = 'auto';
					clearInterval(timer);
				},300);
				ui.main.style.height = ui.currentHeight + "px";
				ui.main.style.top = oTop + 'px';
                window.removeEventListener("touchmove", preventDefault);
				typeof callback == "function" ?  callback({el: _self, type: 'touchend'}) : '';
			})
            function preventDefault(e){
                e.preventDefault();
            }
		}
	}

调用方式:

<script type="text/javascript">
	drag.on({warp:document.querySelector('悬浮按钮')})
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Agoni_轩

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值