优化用于webkit浏览器的javascript浏览器缩放器

时间:2013-05-23 22:28:00

标签: javascript jquery html5 webkit window-resize

我要保持这简短而甜蜜。在webkit浏览器中,我已经应用到[我的网站]的自动缩放器功能似乎响应缓慢[1]当浏览器被调整时,似乎只会出现一些事情。下面是我的JS的片段。

function setTheHeight() {

    if( $('.col-small, .img_hover').length ) {
        //Get value of highest element
        var maxHeight = Math.max.apply(Math, $('.col-small, .img_hover').map (
            function() {
                var totalHeight = 0;

                $(this).children().each(function() {
                    totalHeight += $(this).outerHeight(); 
                });

                return totalHeight;
            }
        ));
        console.log(maxHeight);
        $('.col-small, .img_hover').height(maxHeight);
    }   
}

setTheHeight();

$(window).resize(function() {
    setTheHeight();
});

我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

尝试优化,无需重新计算一些

$('.col-small, .img_hover')

喜欢

.children()

还尝试减少使用map和每个

也许是这样的事情? :

var elems = [], $elems = $('.col-small, .img_hover');

$elems.each(function(i){
    var $t = $(this);
    var $c = $t.children();
    elems[i] = { $:$t, $c:$c, nb:$c.length };
});

function getHeight(e,i){
    var total=0,n=0;
    while(n < e.nb)
        total += e.$c.eq(n++).outerHeight();
    return total;
}

function setTheHeight(){
    $elems.height( Math.max.apply(Math, $.map(elems,getHeight)) );
}

$(window).resize(setTheHeight).resize();

$elems.find("img").on("load",setTheHeight);

您还可以尝试在每次像素更改时都没有完成有效的调整大小

var timer = false;
$(window).resize(function(){
    if(timer !== false) return; // or clearTimeout(timer);
    timer = setTimeout(function(){
        setTheHeight();
        timer = false;
    },20); // 20ms => 50fps max
}).resize();

小提琴=&gt; http://jsfiddle.net/r043v/HvmmM/