正在回答
3回答
你好,可以将css中的定位换成transform,这样在js中设置移动的时候就是在当前移动的基础上进行移动的,可以将移动的距离也传入在函数中,设置在当前的坐标上,参考:



可以按照上图修改测试下,祝学习愉快!
慕用6093692
2019-07-02 14:11:57
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>2-7</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
height: 2000px;
background-color: rgba(255, 192, 203, 0.733);
}
#myDiv {
width: 100px;
height: 100px;
position: relative;
/* 重要!改变了元素的起始位置 */
left: 10px;
background-color: #ff0000;
}
</style>
</head>
<body>
<div id="myDiv"></div>
<script>
drag(myDiv, {
x: true,
y: true
});
function drag(el, options) {
options.x = typeof options.x !== "undefined" ? options.x : true;
options.y = typeof options.y !== "undefined" ? options.y : true;
if (!options.x && !options.y) return;
var curPoint = {
x: 0,
y: 0
},
movePoint = {
x: 0,
y: 0
},
startPoint = {},
isTouchMove = false;
el.addEventListener(
"touchstart",
function(e) {
var touch = e.changedTouches[0];
startPoint.x = touch.pageX;
startPoint.y = touch.pageY;
},
false
);
el.addEventListener(
"touchmove",
function(e) {
isTouchMove = true;
e.preventDefault();
var touch = e.changedTouches[0],
diffPoint = {};
diffPoint.x = touch.pageX - startPoint.x;
diffPoint.y = touch.pageY - startPoint.y;
if (options.x === true) {
movePoint.x = diffPoint.x + curPoint.x;
}
if (options.y === true) {
movePoint.y = diffPoint.y + curPoint.y;
}
move(this, movePoint.x, movePoint.y);
},
false
);
el.addEventListener(
"touchend",
function(e) {
if (!isTouchMove) return;
curPoint.x = movePoint.x;
curPoint.y = movePoint.y;
isTouchMove = false;
},
false
);
function move(el, x, y) {
//得到边界条件
var limitWidth =
document.documentElement.clientWidth - el.offsetWidth,
limitHeight =
document.documentElement.clientHeight - el.offsetHeight;
//判断是否出界
if (x <= 0) {
x = 0;
} else if (x >= limitWidth) {
x = limitWidth;
}
if (y < 0) {
y = 0;
} else if (y > limitHeight) {
y = limitHeight;
}
el.style.transform = "translate3d(" + x + "px, " + y + "px, 0)";
}
}
</script>
</body>
</html>请老师看一下,我设置了元素的 left : 10px ,改变了元素的起始位置。
好帮手慕星星
2019-07-02 11:29:38
你好,
1、可以通过document.documentElement.offsetWidth和document.documentElement.offsetHeight获取页面的宽和高,然后再获取元素的宽高
2、判断元素的位置是否在边界处,例如右侧边界(页面宽度-元素宽度)就是元素在右侧边界的界限。
自己可以试着写一写,如果有问题,可以参考下面这个链接中的回复:
https://class.imooc.com/course/qadetail/126620
祝学习愉快!
3.WebAPP开发与小程序
- 参与学习 人
- 提交作业 622 份
- 解答问题 6815 个
微信带火了小程序,也让前端工程师有了更多的展现机会,本阶段带你从移动基础知识的学习到webAPP开发,及小程序开发,让你PC端与移动端两端通吃。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星