基本上,我希望在我的网站上有一些点,就像" magnet"。如果您接近其中一个,则窗口应滚动到顶部,类似于此jQuery插件:http://benoit.pointet.info/stuff/jquery-scrollsnap-plugin/
问题是,即使页面位于"磁铁的范围内,窗口也不会滚动。
这是jQuery:
$(document).ready( function() {
var magnets = [];
var range = 200;
var active = true;
$('.container').each(function(i,obj) {
magnets.push($(this).offset().top);
});
console.log(magnets);
var attract = function(where,time){
$('html, body').animate({
scrollTop: where
}, time);
active = false;
};
//checks the range of a magnet
var magnetic = function(what){
var top = $(window).scrollTop();
var min = top - range;
var max = top + range;
if( (min <= what) && (max >= what) ){
return true;
} else{
return false;
}
}
//returns, wether you are in range of a magnet from your magnets array or not
var inRange = function(){
var magnet = -1;
for(var i=0; i<magnets.length; i++){
if( magnetic(magnets[i]) == true){
magnet = i;
}
}
return magnet;
}
$(window).scroll(function() {
$('.counter').html("");
$('.counter').append("<p>"+inRange()+"</p>");
if(active == true && inRange != -1){
attract(magnets[inRange()]);
}
else if(active == false && inRange() == -1){
active = true;
}
else if(active == true && inRange() == -1){
console.log("fuck");
}
});
});
替代codepen链接:http://codepen.io/NiclasvanEyk/pen/jEMrZr
答案 0 :(得分:0)
您的代码中存在错误:
if(active == true && inRange != -1){
attract(magnets[inRange()]);
}
应该是
if(active == true && inRange() != -1){
attract(magnets[inRange()]);
}