我试图在数组中找到与另一个数字(用户的浏览器高度)最接近的数字,并且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();

最佳答案

我想你要:

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/

09-26 14:01