在JavaScript中显示/隐藏图像的最佳方式

时间:2012-11-22 10:42:09

标签: javascript show-hide

我在这里阅读了这个问题"Is it faster to swap an img src or show/hide multiple images?"

问题的答案有两个选择。

1)更改图像源 - 页面加载速度更快,交换消耗时间。

2)预加载图像,然后只显示/隐藏 - 页面加载速度稍慢,交换速度更快

对于我的问题,我选择第二个选项,因为加载时间对我来说是第二优先。但有没有最好或最优化的代码编写方式?

假设我从某个地方继续得到数字(10,11,15,25,13,​​19等)。我必须显示许多图像(小点,30个数字,每个图像约1kb)..我也有条件,每个点代表1.5。所以我写了下面的代码。

var dots = new Array(30);

function onBodyLoad() {
    for(var j=0;j<30;j++)
        dots[j] = document.getElementById("dotimg"+j);
}

//called by some method every second.
//argument: the value received from somewhere.

function updateImages(s) {
    var x = Math.round(s);
    var dotPos = x/1.5;
    for(var i=0;i<dotPos;i++) {
        dots[i].style.visibility='visible'; //show that many dots
        document.getElementById('dot-val').textContent=s;//value received shown in span
    }
    for(var j=dotPos;j<30;j++) dots[j].style.visibility='hidden';//hide remaining dots
}

因此,如果一秒钟内收到的值为25,则会显示17个点。如果在下一秒内收到的值为15,则会显示10个点,其余的将被隐藏。有没有更好的方法来编写上面的代码?

1 个答案:

答案 0 :(得分:2)

首先,将'dot-val'设置移出for循环(您在for循环的每次迭代中为其分配相同的值)。
此外,您可以在1循环中更改显示状态,保存for

function updateImages(s) {
    var x = Math.round(s);
    var dotPos = x/1.5;
    for(var i=0;i<30;i++) {
        if(i < dotPos){
            dots[i].style.display='inline-block'; // Assuming they're inline-block elements.
        }else{
            dots[i].style.display='none';
        }
    }
    document.getElementById('dot-val').textContent=s;//value received shown in span
}

现在,如果您真的要修剪代码,请跳过临时x var,并使用Ternary operator

function updateImages(s) {
    var dotPos = Math.round(s)/1.5;
    for(var i=0;i<30;i++) {
        dots[i].style.display = (i < dotPos)? 'inline-block' : 'none';
    }
    document.getElementById('dot-val').textContent = s;//value received shown in span
}