html代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>javascript</title> 6 <link rel="stylesheet" type="text/css" href="index.css"> 7 </head> 8 <body > 9 10 <div class="d1"></div> 11 <div class="d2"> 12 <button onclick="next()">下一个</button> 13 <button onclick="prev()">上一个</button> 14 </div> 15 16 <script> 17 var images = [ 18 'url(img/1.jpg)', 19 'url(img/background.jpg)', 20 'url(img/Bar.jpg)' 21 ]; 22 var num = 0; 23 function next() { 24 var c1 = document.styleSheets[0].rules.length; 25 var c2 = document.styleSheets[0].rules[c1-1]; 26 27 // var slider = document.getElementById("slider"); 28 num++; 29 if(num >= images.length) { 30 num = 0; 31 } 32 c2.style.backgroundImage = images[num]; 33 } 34 function prev() { 35 var c = document.styleSheets[0].rules[2]; 36 num--; 37 if(num < 0) { 38 num = images.length-1; 39 } 40 c.style.backgroundImage = images[num]; 41 } 42 </script> 43 </body> 44 </html>
css代码
1 * { 2 padding: 0; 3 margin: 0; 4 } 5 6 .d2 { 7 position: absolute; 8 bottom: 0; 9 left: 0; 10 width: 200px; 11 height: 200px; 12 background-color: yellow; 13 } 14 15 .d1 { 16 position: absolute; 17 top: 0; 18 left: 0; 19 width: 100vw; 20 height: 100vh; 21 background-image: url('img/1.jpg'); 22 }
说明: 特别注意图片路径正确引用