尝试使div用鼠标滚动从右上角到左下角向相反的滚动方向移动。
现在它从左下角到右上角
#block {
position: absolute;
top: 400px;
left: 100px;
<script>
$(function(){
var lastScrollYPos = 0;
$(window).on('scroll', function(){
var $this = $(this),
$block = $('#block'),
// retrieves the top and left coordinates
position = $block.offset(),
// X and Y factors allows to change the diagonal movement direction and
// degree. Negative values inverts the direction.
factorX = 1,
factorY = 1,
// retrieves current vertical scrolling position and calculate the
// relative offset
scrollYPos = $this.scrollTop(),
offset = Math.abs(scrollYPos - lastScrollYPos),
// mouse wheel delta is inverted respect to the direction, so we need to
// normalize it against the direction
direction = scrollYPos > lastScrollYPos ? -1 : 1,
// calculates the new position. NOTE: if integers only are used for factors,
// then `Math.floor()` isn't required.
newTop = position.top + Math.floor(direction * offset * factorY),
newLeft = position.left - Math.floor(direction * offset * factorX);
// moves the block
$block.offset({ top: newTop, left: newLeft });
lastScrollYPos = scrollYPos;
});
});
</script>
答案 0 :(得分:0)
通过反转方向(如前所述),然后添加最后一个Y位置而不是减去它(我已对此进行评论),我将其翻转了
$(function() {
var lastScrollYPos = 0;
$(window).on('scroll', function() {
var $this = $(this),
$block = $('#block'),
// retrieves the top and left coordinates
position = $block.offset(),
// X and Y factors allows to change the diagonal movement direction and
// degree. Negative values inverts the direction.
factorX = -1,
factorY = -1,
// retrieves current vertical scrolling position and calculate the
// relative offset
scrollYPos = $this.scrollTop(),
// ---- Flip around the offset calculation
offset = Math.abs(scrollYPos + lastScrollYPos),
// mouse wheel delta is inverted respect to the direction, so we need to
// normalize it against the direction
direction = scrollYPos > lastScrollYPos ? -1 : 1,
// calculates the new position. NOTE: if integers only are used for factors,
// then `Math.floor()` isn't required.
newTop = position.top + Math.floor(direction * offset * factorY),
newLeft = position.left - Math.floor(direction * offset * factorX);
// moves the block
$block.offset({
top: newTop,
left: newLeft
});
lastScrollYPos = scrollYPos;
});
});
.body {
height: 1500px;
width: 1000px;
}
#block {
height: 750px;
width: 500px;
background: blue;
position: absolute;
top: -700px;
left: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="body">
<div id="block"></div>
</div>