代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box1 { width: 600px; height: 500px; border: 1px solid #333; text-align: center; margin: auto; } .box1 img { width: 200px; margin-top: 100px; padding: 0px 30px; } </style> </head> <body> <div class="box1"> <img src="../img/img1.jpg" alt="" id="box1img1"> <button id="box1btn">交换</button> <img src="../img/img2.jpg" alt="" id='box1img2'> </div> <script> var img1 = document.querySelector('#box1img1'); var img2 = document.querySelector('#box1img2'); var btn = document.querySelector('#box1btn'); console.log(img1, img2, btn); var flag = 1; btn.onclick = function () { if (flag) { img1.src = '../img/img2.jpg'; img2.src = '../img/img1.jpg'; flag = 0; } else { img1.src = '../img/img1.jpg'; img2.src = '../img/img2.jpg'; flag = 1; } } </script> </body> </html>
效果图: