1

我正在尝试使用 JQuery Waypoints 来做一个变色标题。我有一组对象显示单页网站的各个部分及其相关颜色(见下文):

var colours = new Array(
    {section: 'home', colour: '#000'},
    {section: 'video-audio', colour: '#EF6E7C'},
    {section: 'motion-graphics', colour: '#FBC57A'},
    {section: 'graphic-design', colour: '#FFF9A9'},
    {section: 'web-development', colour: '#AAD693'},
    {section: 'social-media', colour: '#6D8DC9'},   
    {section: 'photography', colour: '#8A6FB0'},    
    {section: 'talent', colour: '#C57AB3'},     
    {section: 'contact', colour: '#000'}
);

然后我使用下面的脚本为每个部分创建 JQuery Waypoints(<section id="...">在 HTML 中标记):

// top bar whose background-colour is being changed
var $topBar = $('.top-bar');

var offsetNum = 0, // pixels to offset waypoints
    animateTime = 300, // milliseconds to animate
    fallbackColour = '#333';

// len is number of sections (length of colours array)
var len = (typeof colours == 'undefined') ? 0 : colours.length;

if (len > 1) {
    for (var i = 0; i < len; i++) {
        var curColour = ('colour' in colours[i]) ? colours[i].colour : fallbackColour,
            curSection = ('section' in colours[i]) ? colours[i].section : 'unknown';

        $('#' + curSection).waypoint(function(direction) {
            if (i > 0 && i < len) {
                curColour = (direction === 'down') ?
                    (colours[i+1].hasOwnProperty('colour') ? colours[i+1].colour : fallbackColour) :
                    (curColour = colours[i-1].hasOwnProperty('colour') ? colours[i-1].colour : fallbackColour);
            }

            // first or last waypoint
            $topBar.stop().animate({backgroundColor: curColour}, animateTime);
        }, { offset: offsetNum });
    }
}

当我只是为每个部分手动创建航点而不是使用对象数组和 for 循环时,它起作用了,但这是很多代码重复。如果稍后添加更多部分,我希望尽可能少做修改。

我在使用警报进行调试时发现所有航点都i显示为 9(它将是最大值) - 有没有办法将正确的i值直接传递给每个航点,或者有没有更好的方法来解决这个问题?

4

1 回答 1

2

在调用回调的那一刻, vari具有值9(所有回调仍然具有对 的相同引用i)。所以你应该传递实际值。例如:

for (var i = 0; i < len; i++) {

    var curSection = ('section' in colours[i]) ? colours[i].section : 'unknown'; 

    addWaypoint(i, curSection);
}

function addWaypoint( n, curSection ){

    // n now has the value 0, 1, 2, etc. instead of referencing i

    $('#' + curSection).waypoint(function(direction) {
        console.log(i, direction); // 0, "down"
    });    
}
于 2013-08-27T09:36:16.740 回答