javascript - 将滚动位置调整到最近的容器

标签 javascript jquery scroll positioning

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

如本网站:http://www.takumitaniguchi.com/tokyoblue/

感谢JUJU

最佳答案

如果你使用 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 选择作为第一个参数即可。

关于javascript - 将滚动位置调整到最近的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11380594/

相关文章:

javascript - 如何根据所选选项调用实例方法?

jQuery UI 选项卡在加载时不隐藏非事件选项卡

javascript - 防止在特定屏幕尺寸的智能手机上滚动

javascript - 如何使用 Google Maps API v3 突出显示地址?

javascript - 如何在没有缓冲的情况下显示完全加载的视频?

javascript - 打印数组元素后跳过一行

android - GridView.scrollTo() 的解决方法?

php - 需要一种在页面刷新后返回滚动窗口位置的方法

javascript - 使用 Jest+Enzyme API 模拟调用进行测试未运行

javascript - 从模板生成的列表中获取 html 数据 - JQuery