javascript - jQuery 不调整滚动位置

标签 javascript jquery scroll

基本上,我想在我的网站上有某些像“磁铁”一样的点。如果您靠近其中之一,窗口应滚动到顶部,类似于此 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");
    }
});
});

替代代码笔链接:http://codepen.io/NiclasvanEyk/pen/jEMrZr

最佳答案

您的代码中有一个错误:

if(active == true && inRange != -1){
    attract(magnets[inRange()]);
}

应该是

if(active == true && inRange() != -1){
    attract(magnets[inRange()]);
}

关于javascript - jQuery 不调整滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628354/

相关文章:

javascript - 如何在 Gatsby 中将环境变量传递给 Sass 插件?

javascript - 如何暂停/停止播放音频并替换为新的音频文件

javascript - 语法错误: Unexpected EOF on closing &lt;/script&gt;

javascript - 如何使页面向下滚动,因为页脚 div 使用 slideDown 扩展得很大?

google-chrome - Chrome 在使用 TinyMCE 时无法滚动

javascript - 我在 Tensorflowjs tf.loadGraphModel 中收到错误 "TypeError: Cannot read property ' Producer' of undefined”

javascript - 如何根据日期对对象数组进行排序

javascript - div 的流体间距

CSS:溢出:滚动;没有出现

c - 在c中逐行(从缓冲区)上下滚动