【发布时间】:2019-01-25 18:13:38
【问题描述】:
试图通过鼠标滚动使 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>
【问题讨论】:
-
它似乎对我有用,你的意思是你希望它在向上滚动时从右上角滚动到左下角吗?
-
当您向下滚动页面时,使其从右上角滚动到左下角。 iv刚刚添加了css
-
在我看来,设置顶部和左侧的方式让它看起来很奇怪。也许尝试非绝对定位 div,这样上下滚动就可以正常工作,而您只需要跟踪左/右。
-
抱歉,在我的个人机器上,我将偏好“滚动方向”设置为关闭。我正在寻找效果,当您滚动时,div 从右上角到左下角对角线进入屏幕
标签: javascript scroll scrolltop