我已经阅读了很多线程,但仍然无法使用不使用快照滚动插件(https://github.com/wtm/jquery.snapscroll)的解决方案。
我试图遵循这个
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);
}
}
我正试图让它滚动到视图
<div class="projectWrap">
小提琴:http://jsfiddle.net/Dar_T/2h2wjp2L/1/
非常类似于此网站http://www.takumitaniguchi.com/tokyoblue/如何滚动其容器。
答案 0 :(得分:1)
首先,您必须找到元素的offset()
。然后将其与$(window.scrollTop())
进行比较,那么您可以进行任何您想要的更改。以下是一些代码:
var project1 = $(".projectWrap").offset();
if($(window).scrollTop() >= project1.top){ // compare window scrolltop to element offset()
$("#tlos1").css("color","blue"); // change navigation
$("#tlos2").css("color","black");
$("#tlos3").css("color","black");
}
这里是DEMO
答案 1 :(得分:0)
试试这个:
var topoffset = 30;
function goTo(tagId) {
var destination = $( '#'+tagId ).offset().top - topoffset;
$("html:not(:animated),body:not(:animated)").animate( { scrollTop: destination}, speed);
});
使用这样的哈希创建网址:
<a href="javascript:goTo('myTagId');">Go to section1</a>