1.判断是向哪边活动(上下左右)
var firstX = 0, firstY = 0, endX = 0, endY = 0;//初始化坐标值
window.addEventListener("touchstart", function (e) {
firstX = e.targetTouches[0].clientX;
firstY = e.targetTouches[0].clientY;
})
window.addEventListener("touchend", function (e) {
endX = e.changedTouches[0].clientX;
endY = e.changedTouches[0].clientY;
moveX = endX - firstX;//判断左右
moveY = endY - firstY;//判断上下
if (Math.abs(moveX) > 60 || Math.abs(moveY) > 60) {//判断是滑动,不是点击
if (Math.abs(moveX) > Math.abs(moveY)){
/*判断横向移动的距离和纵向移动的距离大小对比,判断是左右还是上下*/
var ele = moveX > 0 ? "向右" : "向左";
alert(ele);
}else {
var ele = moveY > 0 ? "向下" : "向上";
alert(ele);
}
}
})
2.移动端或PC模拟移动端网页中测试预览,PC端直接拖拽无效果
<h3>请在移动端或PC模拟移动端网页中测试预览,PC端直接拖拽无效果</h3>
<div class="myk" id="t1"><img src="images/a1.png"></div>
<div class="myk" id="t2" style="left: 150px"><img src="images/a2.png"></div>
<div class="myk" id="t3" style="left: 250px"><img src="images/a3.png"></div>
.myk{width: 100px; height: 100px;background-color: aqua;position: fixed;z-index: 999;top: 150px;left: 50px}
.myk img{width: 100%}
moveDivs("t1"); //传入容器ID就可以
moveDivs("t2");
moveDivs("t3");
//div视野拖拽
function moveDivs(_id){
var _block = document.getElementById(_id);
var _init_left,_init_top,_div_top,_div_left,_box_width,_box_heiht;
var _win_height = $(window).height();
var _win_width = $(window).width();
_block.addEventListener('touchstart', function(e) {
_init_left = parseInt(e.touches[0].clientX);
_init_top = parseInt(e.touches[0].clientY);
_div_top = $("#"+_id).offset().top - $(window).scrollTop();
_div_left = $("#"+_id).offset().left;
_box_width = $("#"+_id).width();
_box_heiht = $("#"+_id).height();
});
_block.addEventListener('touchmove', function(e) {
e.preventDefault();
var _left = parseInt(e.touches[0].clientX);
var _top = parseInt(e.touches[0].clientY);
var _need_left = _div_left + (_left - _init_left);
var _need_top =_div_top + (_top - _init_top);
//检测_block是否还存在可视区域
var _max_left = _win_width - _box_width;
var _max_top = _win_height - _box_heiht;
if(_need_left < 0) _need_left = 0;
if(_need_left > _max_left) _need_left = _max_left;
if(_need_top < 0) _need_top = 0;
if(_need_top > _max_top) _need_top = _max_top;
$(".myk").css({'z-index':9,})
$('#'+_id).css({
'top':_need_top+'px',
'left':_need_left+'px',
'z-index':999,
})
});
_block.addEventListener('touchend', function(e) {
});
}
//保留多位小数
function fixedNum(_val,_num = 2){
var val = (_val * 100) / 100;
return val.toFixed(_num);
}