jQuery实现移动端悬浮拖动效果
模拟手机端悬浮按钮功能,自动吸附两边,并且不能超过活动区域,上下超过自动吸附上或下
因为是移动端端事件,需要调试到移动端才可以看效果
以下是代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script> <title>Document</title> <style> .service_s { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1; display: none; } * { padding: 0; margin: 0; } .content { position: fixed; top: 10%; right: 3%; left: 3%; bottom: 10%; border: 1px solid #cccc77; background: #cccc77; display: flex; align-items: center; color: #fff; font-weight: 600; justify-content: center; } .service { position: fixed; top: 60%; right: 3%; height: 40px; width: 40px; background: #0baefd; z-index:9 } </style> </head> <body> <div class="content">活动区域</div> <div class="service"> <!-- <div class="service_s"></div>--> <!-- 遮罩层--> </div> <script> /** * nx ng 移动坐标 * wxX wxY 初始坐标 * isDown 阻止事件重复触发 * **/ var nx, ny, wxX, wxY, isDown = false; //X Y坐标 // H5页面 $('.service').bind("touchstart", function (e) { //点击触发 e.preventDefault(); $(this).css("transform", 'translate(0)') var touch = event.targetTouches[0]; wxX = touch.clientX; wxY = touch.clientY; // $('.service_s').show() //是否需要一个遮罩层 isDown = true; $(document).bind("touchmove", function (ev) { //滑动触发 e.preventDefault(); if (!isDown) return var touch = event.targetTouches[0]; ny = touch.clientY - $('.service').height() / 2 nx = touch.clientX - $('.service').width() / 2 $('.service').css('top', '' + ny / ($(window).height() / 100) + '%') $('.service').css('left', '' + nx / ($(window).width() / 100) + '%') }) }).bind("touchend", function (e) { //移开触发 var touch = event.changedTouches[0]; //判断跟初始坐标是否一致,一致则大概率为点击事件 if (wxX === touch.clientX && wxY === touch.clientY) { alert('点击了') } else { //判断所在位置,自动吸附左右,如果超过上下活动区域范围则在左右的基础上加上吸附上下 if (nx < $(window).width() / 2) { if ($(window).height() * 0.9 - $('.service').height() < ny) { $('.service').css({"top": "90%", "transform": `translateY(${-($(this).height())}px)`}) } else if ($(window).height() * 0.1 > ny) { $('.service').css({"top": "10%"}) } $('.service').css({"left": "3%",}) } else { if ($(window).height() * 0.9 - $('.service').height() < ny) { $('.service').css({ "top": "90%", "left": "97%", "transform": `translate(${-($(this).height())}px,${-($(this).width())}px)` }) } else if ($(window).height() * 0.1 > ny) { $('.service').css({"top": "10%", "left": "97%", "transform": `translateX(${-($(this).width())}px)`}) } else { $('.service').css({"left": "97%", "transform": `translateX(${-($(this).width())}px)`}) } } } isDown = false; //$('.service_s').hide() }) </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)