首页 > 代码库 > 点击图片改变背景的demo-学习第二天

点击图片改变背景的demo-学习第二天

实例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学习实验课</title>
</head>
<style>
body{
background: url(images/0.jpg)no-repeat;
background-size:cover;
}
.box{
    width:100%;
    height:300px;
}
.inner_image{
    width:1200px;
    height:300px;
    background:gray;
    opacity:0.7;
    margin:0 auto;
}
.inner_image img{
 position: relative;
 float:left;
 width:200px;
 height:200px;
 border:2px solid yellow;
 margin-left: 20px;
 left:40px;
 top:40px;
}
</style>

<body>
    
    <div class="box">
         <div class="inner_image">
                <img src="images/0.jpg" alt="" id="img1"/>
                <img src="images/1.jpg" alt="" id="img2"/>
                <img src="images/2.jpg" alt="" id="img3"/>
                <img src="images/3.jpg" alt="" id="img4" />
                <img src="images/4.jpg" alt="" id="img5" />
         </div>

    </div>

<script>
window.onload=function(){
 var image1=document.getElementById(img1);  
 var image2=document.getElementById(img2);  
 var image3=document.getElementById(img3);  
 var image4=document.getElementById(img4);  
 var image5=document.getElementById(img5); 

 image1.onclick=function(){
  changeImg(0);
 }
  image2.onclick=function(){
  changeImg(1);
 }
  image3.onclick=function(){
  changeImg(2);
 }
  image4.onclick=function(){
  changeImg(3);
 }
  image5.onclick=function(){
  changeImg(4);
 }
 function changeImg(num){
     document.body.style.backgroundImage="url(images/"+num+".jpg)";
 }
}
</script>
</body>
</html>

 

点击图片改变背景的demo-学习第二天