jquery实现移动端悬浮拖拽框
使用jquery 实现了一个基础的悬浮弹拖拽窗, 根据自己的需求去完善动效。 分享给大家供大家参考,具体如下:
演示效果

代码块
需要引入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">
<title>移动端 拖拽按钮</title>
<link rel="stylesheet" href="./static/css/base.css">
<link rel="stylesheet" href="./static/css/index.css">
<!-- js -->
<script src="./static/js/jquery-3.5.1.js"></script>
</head>
<body>
<div class="main">
<div class="circle-box" ontouchmove="touchMove(event)" ontouchend="touchEnd()">
<div class="circle"></div>
</div>
</div>
</body>
</html>
<script>
var startX = 0;
var startY = 0;
$(function () {
$('.circle-box').on('touchstart', function (event) {
var element = event.targetTouches[0];
// 初始化位置
startX = element.pageX - this.offsetLeft;
startY = element.pageY - this.offsetTop;
console.log(startX, startY);
return false
})
})
function touchMove(event) {
var element = event.targetTouches[0];
var x = element.clientX - startX;
var y = element.clientY - startY;
parentWidth = $('.main').innerWidth();
parentHeight = $('.main').innerHeight();
// 设置 上边界
if (y <= 0) {
y = 1;
}
// 设置 下边界 40: 移动框自身宽度
if (y >= parentHeight - 40) {
x = parentHeight - 40 - 1;
}
// 设置 左边界
if (x <= 0) {
x = 1;
}
// 设置 右边界 40: 移动框自身宽度
if (x >= parentWidth - 40) {
x = parentWidth - 40 - 1;
}
$('.circle-box').css({
'left': x + 'px',
'top': y + 'px'
})
return false
}
function touchEnd(event) {
$('.main').unbind('mousemove')
$('.main').unbind('mouseup')
}
</script>
CSS
基础css 根据自己需求修改
.main {
position: relative;
overflow: hidden;
width: 100vw;
height: 100vh;
background: pink;
padding: 1px;
box-sizing: border-box;
}
.circle-box {
position: absolute;
top: 200px;
bottom: 0;
/* 如果初始化设置right, 需先隐藏left, left级别大于right*/
/* left: 0; */
right: 1px;
width: 40px;
height: 40px;
line-height: 40px;
border-radius: 50%;
background-color: transparent;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3);
z-index: 999;
}
.circle-box .circle {
width: 30px;
height: 30px;
border-radius: 50%;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
background-color: #fff;
opacity: 0.5;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)
