js動態切換圖片的方法,js動態切換

來源:互聯網
上載者:User

js動態切換圖片的方法,js動態切換

本文執行個體講述了js動態切換圖片的方法。分享給大家供大家參考。具體實現方法如下:

index.css檔案如下:

複製代碼 代碼如下:* { 
    margin: 0px;padding: 0px; 

 
body { 
    width: 632px; 
    /*background-color: blue;*/ 
    margin: 0 auto; 

 
#imgsCom { 
    background-color: yellow; 
    /*相對定位,為了下層可以使用絕對位置時以本div的原點為原點*/ 
    position: relative; 

 
#ulnav{ 
    list-style-type: none; 
    
    position: absolute; 
    /*使用以imgsCom為原點來絕對位置到右下角*/ 
    bottom: 0px; 
    right: 0px; 

#ulnav li{ 
    list-style-type: none; 
    float: left; 
    background-color: black; 
    color: white; 
    margin-right: 5px; 
    width: 20px; 
    height: 20px; 
    line-height: 20px; 
    text-align: center; 
    cursor: pointer; 
}

index.html如下:
複製代碼 代碼如下:<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>js,css動態切換圖片</title> 
    <link href="css/index.css" rel="stylesheet" /> 
    <script type="text/javascript"> 
 
        function gel(id) { 
            return document.getElementById(id); 
        } 
 
        function  clearLiBg() { 
            var mylis = gel("ulnav").childNodes; 
            for (var i = 0; i < mylis.length; i++) { 
                if (mylis[i].nodeType == 1) { 
                    mylis[i].style.backgroundColor = "black"; 
                } 
            } 
        } 
       
        window.onload = function() { 
            //給三個li都指定一個屬性 
            var lis = gel("ulnav").childNodes; 
            for (var i = 0; i < lis.length; i++) { 
                if (lis[i].nodeType == 1) { 
                    lis[i].onclick = function () { 
                        //更換圖片 
                        gel("myimg").setAttribute("src", "images/" + this.innerHTML + ".png"); 
                        //所有LI顏色複原 
                        clearLiBg(); 
                        //更換LI背景標籤顏色 
                        this.style.backgroundColor = "silver"; 
                    }; 
                } 
            } 
        }; 
    </script> 
</head> 
<body> 
    <div id="imgsCom" style="width: 632px; height: 412px;"> 
        <img src="images/1.png" id="myimg" style="width: 632px; height: 412px; " /> 
        <ul id="ulnav"> 
            <li>1</li> 
            <li>2</li> 
            <li>3</li> 
        </ul> 
    </div> 
</body> 
</html>

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.