我正在使用jQueryUI在移动设备上构建可拖动内容。
我设计了此可拖动内容,以便仅水平滑动,并增加了内容不能滚动出其容器的限制。效果很好。
我还希望用户能够按照用户的手势垂直拖动以使整个文档向上滚动并完成。我正在尝试不成功地使用$('body')。scrollTop():以正确的方式水平拖动,根本不垂直移动。
能请你帮我吗?
密码笔在这里:https://codepen.io/MaxAurray/pen/Krawxj
HTML:
<html>
<head></head>
<body>
<!-- DEBUG FRAME -->
<div class="debug">
<div class="body"></div>
<div class="drag"></div>
</div>
<!-- DUMMY CONTENT -->
<div class="content">Dummy content</div>
<!-- INTERESTING PART -->
<div class="container">
<h2>Beautiful images</h2>
<h3>(drag left and right)</h3>
<div class="draggable">
<div class="card">
<img src="https://picsum.photos/200/150/?random1">
<h3>Image 1</h3>
</div>
<div class="card">
<img src="https://picsum.photos/200/150/?random2">
<h3>Image 2</h3>
</div>
<div class="card">
<img src="https://picsum.photos/200/150/?random3">
<h3>Image 3</h3>
</div>
<div class="card">
<img src="https://picsum.photos/200/150/?random4">
<h3>Image 4</h3>
</div>
</div>
</div>
<!-- DUMMY CONTENT -->
<div class="content">Dummy content</div>
</body>
</html>
CSS:
body {
margin: 50px;
}
.debug {
position:fixed;
top:0;
right:0;
width:200px;
height:100px;
border:1px blue dashed;
}
.content {
display:flex;
justify-content: center;
align-items:center;
background-color:rgba(0,0,0,0.2);
width:500px;
height:300px;
font-style: italic;
}
.container {
width:500px;
background-color:rgba(255,0,0,0.2);
overflow-x:hidden;
h2,h3 {
text-align:center;
}
.draggable {
background-color:rgba(0,255,0,0.2);
padding:20px 0;
display: flex;
width:(66% * 4);
justify-content: space-between;
.card {
width: 100%;
border:1px rgba(0,0,255,0.2) dashed;
background-color:rgba(0,0,255,0.2);
text-align:center;
img {
width:200px;
height:150px;
}
}
}
}
JavaScript:
/*
This code pen imports:
- jQuery,
- jQuery UI,
- jQueryUI-Touch-Punch
*/
$(document).ready(function() {
$(".draggable").draggable({
// Save body position at drag begin
start: function(event, ui) {
$("body").data("top", $("body").scrollTop());
},
drag: function(event, ui) {
// Debug display
$(".debug .body").text("BODY - ScrollTop: " + (parseInt($("body").data("top")) - ui.position.top));
$(".debug .drag").text(
"DRAG - Top:" + ui.position.top + " / Left: " + ui.position.left
);
// Move body vertically, relative to drag position
$("body").scrollTop(parseInt($("body").data("top")) - ui.position.top);
// Get card width
var intDivLength = $(this)
.find("div:first-child")
.outerWidth();
// Do not allow to go left after first image
if (ui.position.left > 0) {
ui.position.left = 0;
} else if (
// Do not allow to go right after last image
ui.position.left <
-4 * intDivLength +
$(this)
.closest(".container")
.innerWidth()
) {
ui.position.left =
-4 * intDivLength +
$(this)
.closest(".container")
.innerWidth();
}
// Force move on x axys.
ui.position.top = 0;
},
scroll: false
});
});