用javascript预加载切换图像?

时间:2013-05-01 08:17:15

标签: javascript image

我必须在非常短的时间内显示图像,50毫秒(这是第一次印象测试),但每次用户点击按钮时通过设置src来切换图像会造成太大的延迟。这是代码:

HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Studio usabilità</title>
        <link rel="stylesheet" href="style.css" > 
        <script type="text/javascript" src="myscripts.js"></script>
    </head>
    <body>
        <div class="container">
            <div class="action_panel">
                <div class="label">
                    ISTRUZIONI: Nell'istante in cui si clicca su un bottone, viene aperta la pagina corrispondente
                    nello spazio bianco sotto questa sezione. L'immagine verrà visualizzata per un tempo molto breve.
                </div>
                <button class="button" id='btn1' onclick='javascript:changeImage("prova.jpg","btn1","false");'>PROVA</button>
                <button class="button" id='btn2' onclick='javascript:changeImage("sito1.jpg","btn2","true");'>SITO #1</button>
                <button class="button" id='btn3' onclick='javascript:changeImage("sito2.jpg","btn3","true");'>SITO #2</button>
            </div>
            <img src="" class="image" id="image" alt=""/>
        </div>
    </body>
</html>

CSS:

root { 
display: block;
}

body, html { /* set size of body to full page and remove margins */
    width: 100%;
    height: 100%;
    padding: 0;
    margin: 0;
}

.action_panel {
    margin: auto;
    text-align: center;
    position: absolute; 
    height: 40px; 
    width: 100%; 
    background-color: darkslategrey;
}

.button {
    float: left;
    margin-top: 6px;
    margin-left: 10px;
    width:100px;
    height: 28px;
    background-color:activecaption;
}

.image {
    margin-top: 40px;
    margin-left: 300px;
    height: 600px;
    display: none;
}

.label {
    width: 850px;
    float: left;
    color: gainsboro;
    margin-left: 40px;
    margin-right: 40px;
    text-align: left;
}

JAVASCRIPT:

function changeImage(img, btn, disable) {
    var obj = document.getElementById('image');
    obj.src = img;
    obj.style.display = 'inline';
    setTimeout(
        function() {
            obj.style.display = 'none'
        }, 50);
    this.disabled = 'disabled';
    if (disable == "true")
        document.getElementById(btn).disabled = 'true';
}

1 个答案:

答案 0 :(得分:0)

您也可以保留三张图片并设置更改其显示,如您所说,每隔50毫秒, 使用

obj.style.display = "none"

每次单击按钮时,无需保留单个图像元素并更改其src。