水平滚动后的 jQuery 捕捉

标签 jquery html css mousewheel

我有一个使用鼠标滚轮 jQuery 插件的水平滚动网站。滚动有效,但我想将每个“文章”捕捉到文档的左侧,这样一旦停止滚动,它就不会停留在一半的位置。

我目前的标记:

CSS

#viewport {
width:100%;
height:100%;
overflow: hidden;
}

#stage {
height:100%;
width:400%;
position: absolute;
display:block;
overflow: hidden;
}

#stage article {
width:25%;
height:100%;
position: relative;
display:block;
float:left;
}

HTML

<div id="viewport">
<section id="stage" class="clearfix">
<article>
This is the block that should snap to the left once scrolling is stopped.
</article>

<article>
This is the block that should snap to the left once scrolling is stopped.
</article>

<article>
This is the block that should snap to the left once scrolling is stopped.
</article>

<article>
This is the block that should snap to the left once scrolling is stopped.
</article>

</section>
</div>

JQUERY

$(function() {
$("html, body").mousewheel(function(event, delta) {
this.scrollLeft -= (delta * 30);
event.preventDefault();
});
});

我尝试使用这个脚本,但没有什么好结果。似乎百分比阻止了知道上一个/下一个位置。

https://stackoverflow.com/a/8170667

提前致谢。

最佳答案

我不知道你所说的上一个/下一个位置是什么意思。

但是您可以在每次滚动结束时检查屏幕左侧是否位于最近的文章上。如果没有,请滚动得更近一些。

也许像...

$(function() {
    $("html, body").mousewheel(function(event, delta) {

        var theBody = $('body');
        theBody.scrollLeft(this.scollLeft() - delta * 30);

        /* Snap how close, how many articles, and what direction is the scroll? */
        var tolerance = 10;
        var numberOfArticles = 4;
        var signDelta = number?number<0?-1:1:0;

        /* While you're not within an acceptable tolerance, get a little closer */
        while (!((theBody.scollLeft()%(theBody.width() / numberOfArticles))  > tolerance))
        {
            theBody.scrollLeft(theBody.scollLeft() - signDelta * 1);
        }

        event.preventDefault();
    });
});

关于水平滚动后的 jQuery 捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389686/

相关文章:

javascript - 如何阻止 JavaScript 文件在 JavaScript 中下载两次?

javascript - 如何在没有滚动条(实际滚动)的情况下增加滚动上的数字?

html - CSS定位: absolute/relative overlay

jquery - 如何在网页打开后立即制作jquery效果

jquery - Bootstrap - 在调整大小时从一组 div 中向下移动一个 div

html - 使表格单元格的边框为表格宽度的 100%

css - 无缝图像对齐,无论 CSS 的方向如何?

javascript - 使用 Javascript 的 window.print 中的对齐问题

javascript - 捕获退格键事件

javascript - 使用未转义的 HTML 以字符串形式获取元素的内容