【问题标题】:Adjust scroll position to a nearest container将滚动位置调整到最近的容器
【发布时间】:2012-07-09 00:29:32
【问题描述】:

我目前正在寻找一个 JavaScript(例如 Jquery lib)解决方案来将滚动的位置调整到特定的 css 类。目标是在最近的容器上重新定位滚动条。

作为本站:http://www.takumitaniguchi.com/tokyoblue/

感谢JUJU

【问题讨论】:

    标签: javascript jquery scroll positioning


    【解决方案1】:

    如果您使用 JQuery,如果我正确理解了您的问题,则相对容易实现。 以下是我的大致方法:

    function scrollTo(a){
        //Get current scroll position
        var current = (document.all ? document.scrollTop : window.pageYOffset);
        //Define variables for data collection
        var target = undefined;
        var targetpos = undefined;
        var dif = 0;
        //check each selected element to see witch is closest
        $(a).each(function(){
            //Save the position of the element to avoid repeated property lookup
            var t = $(this).position().top;
            //check if there is an element to check against
            if (target != undefined){
                //save the difference between the current element's position and the current scroll position to avoid repeated calculations
                var tdif = Math.abs(current - t);
                //check if its closer than the selected element
                if(tdif < dif){
                    //set the current element to be selected
                    target = this;
                    targetpos = t;
                    dif = tdif;
                }
            } else {
                //set the current element to be selected
                target = this;
                targetpos = t;
                dif = Math.abs(current - t);
            }
        });
        //check if an element has been selected
        if (target != undefined){
            //animate scroll to the elements position
            $('html,body').animate({scrollTop: targetpos}, 2000);
        }
    }
    

    这可能不是最好的方法,但应该可以。只需调用该函数并将 JQuery 选择作为第一个参数传递。

    【讨论】:

    • 现在试一试,只需将 $('.cover2') 作为您案例中的第一个参数传递
    • 我已经修复了它,我已经在你的网站上对其进行了测试,它对我有用。我在编辑过程中放错了右括号。
    猜你喜欢
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多