1 <style> 2 *{ 3 margin: 0;padding: 0; 4 list-style: none; 5 } 6 body{ 7 background: black; 8 } 9 .outer{ 10 margin: 10px auto; 11 border: 1px solid white; 12 border-radius: 6px; 13 background-color: white; 14 width: 200px; 15 padding: 8px 6px 6px 8px; 16 } 17 .outer>ul{ 18 overflow: hidden; 19 } 20 21 .outer>ul>li, .outer>ul>li>img{ 22 /* 兩個部分設置內容一樣,選擇器寫在一起。 */ 23 float: left; 24 width: 48px; 25 height: 48px; 26 /* li的寬高不能直接由內部img撐起? */ 27 28 margin: 0 2px 2px 0; 29 } 30 /* .outer>ul>li>img{ 31 width: 48px; 32 height: 48px; 33 } */ 34 .outer>ul>li:nth-child(1){ 35 position:relative; 36 /* 相對定位,子絕父相,給后面的loading動態圖div使用。 */ 37 } 38 .outer>ul>li:nth-child(1), .outer>ul>li:nth-child(1)>img{ 39 /* 兩個部分設置內容一樣,選擇器寫在一起。 */ 40 width: 148px; 41 height: 148px; 42 } 43 44 .outer>li.first div{ 45 position:absolute;top:0;left:0; 46 width:156px;height:156px; 47 display:none; 48 opacity:0.5;filter:alpha(opacity=50); 49 background:#fff url(img/loading.gif) 50% 50% no-repeat; 50 /* 給第一個大圖li加一個空div,添加loading的背景圖。 讓圖片加載時,顯示加載動圖 */ 51 } 52 </style> 53 54 <script> 55 window.onload = function() 56 { 57 // var aImg = document.getElementsByTagName('img'); 58 59 // for(let i=0; i<aImg.length; i++) 60 // { 61 // aImg[i].onmouseover = function() 62 // { 63 // aImg[0].src = this.src; 64 // }; 65 // }; 66 67 var oImg = document.getElementById("box").getElementsByTagName("img"); 68 69 var oDiv = document.getElementsByTagName("div")[0]; 70 // 給第一個大圖li加一個空div,添加loading的背景圖。 讓圖片加載時,顯示加載動圖。 71 for (var i = 1; i < oImg.length; i++) 72 { 73 oImg[i].onmouseover = function () 74 { 75 var img = new Image(); 76 77 img.src = oImg[0].src = this.src.replace(/small/,"big"); 78 // replace(); 方法,用於在字符串中用一些字符替換另一些字符。 79 // 例如: 80 // var str="Visit Microsoft!" 81 // document.write(str.replace(/Microsoft/, "W3School")) 82 // 輸出:Visit W3School! 83 84 oDiv.style.display = "block"; 85 86 img.complete ? oDiv.style.display = "none" : (oImg[0].onload = function() {oDiv.style.display = "none"}) 87 // complete 通過Image對象的complete 屬性來檢測圖像是否加載完成。 88 // onload 當圖像裝載完畢時調用的事件句柄。 89 90 // 所以上面這個三元表達式的意思是: 91 // img這個圖片對象是否加載完成? 92 // 加載完成就讓div的display為none。 沒有加載完成,就調用img的onload事件,讓它加載完成,然后運行function 讓div的display為none。 93 94 // js Image()對象onload和預加載 95 // https://segmentfault.com/a/1190000011020722?utm_source=tag-newest 96 } 97 } 98 }; 99 </script>