原生JavaScript实现换肤
原生JavaScript实现换肤的具体代码,供大家参考,具体内容如下
原理
通过点击事件,获取点击的的图片的信息,在HTML背景图片的路径改变
css样式
<style> body{ margin:0; padding:0; background:url(img/1.jpg) no-repeat; background-size:100% 100%; } #box{ width:100%; height:130px; background:#999999; } #box ul{ margin:0; padding:0; list-style:none; } #box ul li li,#box ul li img{ width:180px; height:120px; float:left; margin:5px 60px; }</style>
HTML源码
<body id='Body'> <div id='box'> <ul> <li><img src='https://www.haobala.com/bcjs/img/1.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/2.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/3.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/4.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/5.jpg' /></li> </ul> </div></body>
JavaScript源码
<script> var oBody=document.getElementById(’Body’); var oImg=document.getElementsByTagName(’img’); for(var i=0;i<oImg.length;i++) { var oImgA=oImg[i]; oImgA.index=i+1; oImgA.onclick=function(){ //console.log(this); oBody.style.background=’url(img/’+this.index+’.jpg) no-repeat’; oBody.style.backgroundSize=’100% 100%’; }; }</script>
效果图
点击切换
源码
<!DOCTYPE><html lang='en'><head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /> <title>换肤</title> <style> body{ margin:0; padding:0; background:url(img/1.jpg) no-repeat; background-size:100% 100%; } #box{ width:100%; height:130px; background:#999999; } #box ul{ margin:0; padding:0; list-style:none; } #box ul li li,#box ul li img{ width:180px; height:120px; float:left; margin:5px 60px; } </style></head><body id='Body'> <div id='box'> <ul> <li><img src='https://www.haobala.com/bcjs/img/1.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/2.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/3.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/4.jpg' /></li> <li><img src='https://www.haobala.com/bcjs/img/5.jpg' /></li> </ul> </div></body></html><script> var oBody=document.getElementById(’Body’); var oImg=document.getElementsByTagName(’img’); for(var i=0;i<oImg.length;i++) { var oImgA=oImg[i]; oImgA.index=i+1; oImgA.onclick=function(){ //console.log(this); oBody.style.background=’url(img/’+this.index+’.jpg) no-repeat’; oBody.style.backgroundSize=’100% 100%’; }; }</script>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章: