JavaScript实现更换背景图片
人气:0主要通过Js控制行内样式,达到更换背景图片的目的
效果:
代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>更换背景</title> <style type="text/css"> *{ margin: 0; padding: 0; } body{ background: url(./images/01.jpg) no-repeat; background-size: 600px; } ul{ list-style: none; } ul li{ width: 80px; height: 50px; border: 1px solid #222; float: left; margin: 10px; } ul li img{ width: 80px; height: 50px; cursor: pointer; } </style> <script type="text/javascript"> window.onload = function(){ var imgs = document.getElementsByTagName("img"); for (var i = 0; i < imgs.length; i++) { imgs[i].onclick = function(){ document.body.style.background = "url("+this.src+") no-repeat";//通过js控制改变行内样式 document.body.style.backgroundSize = "600px"; } } } </script> </head> <body> <ul> <li><img src="./images/01.jpg" ></li> <li><img src="./images/02.jpg" ></li> <li><img src="./images/03.jpg" ></li> </ul> </body> </html>
注意:
正确写法: document.body.style.background = “url(”+this.src+") no-repeat";
错误写法: document.body.style.background = "this.src“ no-repeat;
您可能感兴趣的文章:
加载全部内容