正如您在此链接中所看到的:https://www.tumblr.com/explore/text 当我们点击并向左和向右拖动主题标签时,它们将自动移回原始位置。
现在我可以创建我的链接,这意味着< a>元素,向左和向右移动,但如果我拖得太多,它们就无法恢复到原来的位置。我的工作在这里:https://codepen.io/victorcruzte/pen/oxMYJw
HTML:
<div class="parent">
<div class="children">
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
</div>
</div>
CSS:
.parent {
margin: 200px auto;
width: 200px;
height: 100px;
overflow: hidden;
border: 1px solid #000;
}
.children {
float: left;
white-space: nowrap;
}
JS:
var x1, x2 = 0, x3;
var click = false;
var temp = 0, temp2, temp3 = 0;
function draga() {
$('.children a').click(function(e) {
e.preventDefault();
});
$('.children').mousedown(function(e) {
click = true;
x1 = e.pageX;
});
$(document).mouseup(function() {
click = false;
});
$('.children').mousemove(function(e) {
if (click === false) return;
e.stopPropagation();
(temp3 != x1) ? (temp2 = 0) : (temp2 = x2);
temp3 = x1;
x2 = e.pageX;
(temp2 === 0) ? x3 = (x2 - x1) : x3 = (x2 - temp2);
temp += x3;
$(this).css('background-color', 'pink');
$(this).css('transform', 'translate('+ temp + 'px, 0px');
});
};
$(window).load(function() {
draga();
});
我是jquery的新手,所以希望你能帮助我。非常感谢你!
答案 0 :(得分:0)
我想我解决了你的问题并希望它会有所帮助。 请参阅下面的代码和摘要:
你遗漏的是当儿童元素出现在同一元素时的检查。
var xStart = 0;
var xStop = 0;
var xDelta = 0;
function draga() {
$('.children').find('a').attr('onmousedown', 'return false')
$('.children a').click(function(e) {
e.preventDefault();
});
$('.children').mousedown(function(e) {
xStart = e.pageX;
$(document).mousemove(function(e) {
xDelta = parseInt((e.pageX + xStop) - xStart);
$('.children').css('transform', 'translate(' + xDelta + 'px, 0)');
})
});
$(document).mouseup(function(e) {
if (xDelta > 185) {
$({ Counter: xDelta }).animate({ Counter: 0 }, {
duration: 500,
step: function () {
$('.children').css('transform', 'translate('+ this.Counter +'px, 0)');
}
});
xDelta = 0;
} else if (xDelta < -($('.children').width() - 15)) {
xDelta += Math.abs($('.children').width() - Math.abs(xDelta)) + 200;
$({ Counter: -$('.children').width() }).animate({ Counter: xDelta }, {
duration: 500,
step: function () {
$('.children').css('transform', 'translate('+ this.Counter +'px, 0)');
}
});
}
xStop = xDelta;
$(document).off("mousemove");
})
}
$(window).load(function() {
draga();
});
&#13;
.parent {
margin: 50px auto;
width: 200px;
height: 100px;
overflow: hidden;
border: 1px solid #000;
}
.children {
float: left;
white-space: nowrap;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="parent">
<div class="children">
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
<a href="#">abcdefg</a>
</div>
</div>
&#13;