0

我试图在一个数组中找到最接近另一个(用户的浏览器高度)并且h是随机的数字-Infinity。这是我的代码。

function match_height() {
    var heights = [11, 630, 693, 756, 819, 882, 945, 1008, 1071, 1134, 1197, 1260, 1323, 1386, 1449, 1512, 1575, 1638, 1701, 1764, 1827, 1890, 1953, 2016, 2079, 2142, 2205, 2268, 2331, 2394, 2457, 2520];
    var posb = [];

    var browsery = $(window).height();

    for (var i = 0; i < heights.length; i++) {
        if (browsery > heights[i] && heights[i + 1] <= browsery) {
            posb.push(heights[i+1]);
        }
    }

    var h = Math.max.apply(Math, posb);

    $(".area").css("height", h + "px");
    $(".area").css("width", "100%");
    $(".ground").css("background", "url(scenes/ground/" + h + ".png)");
}

match_height();
4

3 回答 3

4

我想你想要:

if ( browsery > heights[i] && browsery <= heights[i+1] ) {

在您当前的代码中,您的posb数组永远不会填充任何值。


顺便说一句,考虑一下:

var heights = [ ... ];
var winHeight = $( window ).height();
var i = 0;

while ( winHeight > heights[i] ) i++;

var h = heights[i];

现场演示:http: //jsfiddle.net/489La/

于 2012-08-05T02:17:06.580 回答
0

您忘记考虑高度大于您列出的所有选项的情况。

如果你运行Math.max.apply(Math,[]),你会看到它的结果-Infinity。这意味着您的posb数组是空的。

于 2012-08-05T02:16:57.290 回答
0

这是我的版本:http: //jsfiddle.net/pm7C3/

function match_height() {
    var heights = [11, 630, 693, 756, 819, 882, 945, 1008, 1071, 1134, 1197, 1260, 1323, 1386, 1449, 1512, 1575, 1638, 1701, 1764, 1827, 1890, 1953, 2016, 2079, 2142, 2205, 2268, 2331, 2394, 2457, 2520];

    var match = null,
        closest = -1,
        browsery = $(window).height();

    for (var i = 0; i < heights.length; i++) {
        var diff = Math.abs(browsery - heights[i]);
        if (closest == -1 || diff < closest) {
            closest = diff;
            match = heights[i];
        }
    }

    $(".area").css("height", match + "px");
    $(".area").css("width", "100%");
    $(".ground").css("background", "url(scenes/ground/" + match + ".png)");
}
于 2012-08-05T02:24:03.097 回答