javascript - 使 jQuery 路点相对偏移

标签 javascript jquery jquery-waypoints

您知道刷新网页时通常如何保留滚动位置吗?

好吧,jQuery Waypoints偏移功能似乎将此页面位置用作 0,而不是页面的实际顶部。

例如,给定路径点偏移量为 50,假设页面刷新时当前的滚动位置为 1000。刷新后的页面会自动跳回1000。滚动位置达到1050时,该航点才会激活。

是否可以保持相对于页面顶部的航路点?因此,即使页面自动更新,滚动位置为 1000 的航路点偏移量为 50 也将处于事件状态。

$('.thing').waypoint(function(direction) {
    // do stuff
}, { offset: 50 })

更详细的代码:

(function($, window, document) {

    $(function() {

        var $popularArticles = $('.popular').find('article'),
        $latestArticles = $('.latest').find('article');

        var $latestPost = $latestArticles.filter(':first');
        var $latestPostDate = $latestPost.find('time').text();

        $latestPost.before('<h2>' + $latestPostDate + '</h2>');
        $popularArticles.filter(':first').before('<h2>Popular Now</h2>');

        // updates postdate in latest h2

        $latestArticles.waypoint(function(direction) {
            var $postDate = $(this).find('time').text();
            if (direction === 'down') {
                $latestH2.text($postDate);
            }
        }, { offset: 102 }).waypoint(function(direction) {
            var $postDate = $(this).find('time').text();
            if (direction === 'up') {
                $latestH2.text($postDate);
            }
        }, { offset: function() {
            return - $(this).height() / 2 + 50;
            }
        });

        // h2 waypoints

        var $latestH2 = $('.latest').filter(':first').find('h2'),
            $popularH2 = $('.popular').filter(':first').find('h2');

        $popularH2.add($latestH2).waypoint('sticky', { offset: 50 });

    });

}(window.jQuery, window, document));

最佳答案

认为浏览器在页面加载之后才会跳转到滚动位置,因此请尝试在页面加载之前而不是加载时运行路径点代码。

关于javascript - 使 jQuery 路点相对偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24560074/

相关文章:

java - 动态构建数据表与脚本

jquery - 确定 <div> 内 <p> 总量的最大高度

javascript - 如何检测调用 jquery 脚本的内容

javascript - 如何在Javascript中将数组插入数组?

jquery - 使用航路点更改导航上的 li 背景

javascript - 当我的 React 组件通过 AJAX 获取时显示加载旋转器/gif 的最佳方式?

javascript - JavaScript 中的 "=>"运算符

javascript - 一个奇怪的关闭案例。谁能解释这是如何工作的?

jquery-waypoints - Waypoints 3.0 中的 triggerOnce 选项发生了什么变化?