我目前正在寻找一个JavaScript(例如Jquery lib)解决方案来调整滚动到特定css类的位置。目标是在最近的容器上重新定位滚动条。
正如本网站:http://www.takumitaniguchi.com/tokyoblue/
感谢JUJU
答案 0 :(得分:4)
如果您使用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选择作为第一个参数传递。