最近做一个项目,其中包含了页面上拖拽排序功能,使用了jquery ui中的拖拽功能。
jQuery UI draggable
引入jquery-ui.min.js
结构:
<div class="wear-medals-list-con">
<ul class="wear-medals-list" style="width: 114px;">
....
<li class="wml-item unlock-item">
<div class="medal-img-con">
<img alt="medal" src="giftsyn/gift/40292s.1.png">
</div>
<p class="medal-time-tip">
<span>7天</span>
</p>
</li>
....
</ul>
</div>
function item_drag() {
$(".wear-medals-list").sortable({
containment:".wear-medals-list",
cancel:".add-time-con",
revert:true,
start: function() {
console.log('start');
},
sort: function() {
console.log('sort');
},
stop: function(e) {
console.log('stop');
}
});
}
实际检查元素可以看到原有的样式上新增了拖拽相关的样式
<ul class="wear-medals-list ui-sortable" style="width: 114px;">
<li class="wml-item unlock-item ui-sortable-handle">
<div class="medal-img-con">
<img alt="medal" src="giftsyn/gift/40292s.1.png">
</div>
<p class="medal-time-tip">
<span>7天</span>
</p>
</li>
</ul>
移动端也可使用,但是jQyery UI不是为移动端而写的,因此在手机上无效。需再加一个jQuery UI Touch Punch插件即可。
即除了item_drag()外,必须添加如下事件:https://blog.youkuaiyun.com/xiaoxiaohui520134/article/details/82996868?tdsourcetag=s_pcqq_aiomsg
var touchValue = { x: 5, y: 5, sx: 0, sy: 0, ex: 0, ey: 0 }; //initialize the touch values
window.addEventListener("touchstart", function () {
console.log("touchstart")
var event = event || window.event;
touchValue.sx = event.targetTouches[0].pageX;
touchValue.sy = event.targetTouches[0].pageY;
touchValue.ex = touchValue.sx;
touchValue.ey = touchValue.sy;
});
window.addEventListener("touchmove", function (event) {
var event = event || window.event;
// event.preventDefault(); 会阻止页面上下滑动
touchValue.ex = event.targetTouches[0].pageX;
touchValue.ey = event.targetTouches[0].pageY;
console.log("touchmove")
}, {passive: false});
window.addEventListener("touchend", function (event) {
var event = event || window.event;
var changeX = touchValue.ex - touchValue.sx;
var changeY = touchValue.ey - touchValue.sy;
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
console.log("touchend")
});
注意:https://www.jianshu.com/p/04bf173826aa
1、使用event.preventDefault(); 带来的问题:
1)使用了event.preventDefault();可能会影响到移动端页面的上下滑动。
2)上面滑动时候控制台给出的警告:Unable to preventDefault inside passive event listener
解决方案一:在touch的事件监听方法上绑定第三个参数{ passive: false },通过传递 passive 为 false 来明确告诉浏览器:事件处理程序调用 preventDefault 来阻止默认滑动行为。如上touchmove添加了{passive: false}解决:
elem.addEventListener(
'touchstart',
fn,
{ passive: false }
);
解决方案二:
* { touch-action: pan-y; }
使用全局样式样式去掉
2、实际应用上面拖拽特别是移动端会受到样式布局影响
实际测试:移动端横向滚动的时候,实现拖拽受到以下布局影响:
1)横向滚动的横向排列样式:用display: flex强制一行,导致拖拽不灵敏,可拖拽,但是放置很难成功
2)外面的ul根据其中的li标签自动撑开,li使用display: inline-block或float: left实现横向排列导致出现滚动条时,不能拖动到下一页 =>ul根据li标签个数自动计算宽度+li-float: left