思路:给图片添加循环注册点击事件,当我们点击图片,这张图片就会成为当前页面的背景图。算法:将点击的图片的地址取出,给body作为背景图。
var img = document.querySelector(".hf").querySelectorAll(“img”);获取的img返回的是伪数组形式,所以遍历获取的img可以得到当前点击的图片的信息。
<!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>
@font-face {
font-family: 'icomoon';
src: url('fonts/icomoon.eot?tomleg');
src: url('fonts/icomoon.eot?tomleg#iefix') format('embedded-opentype'),
url('fonts/icomoon.ttf?tomleg') format('truetype'),
url('fonts/icomoon.woff?tomleg') format('woff'),
url('fonts/icomoon.svg?tomleg#icomoon') format('svg');
font-weight: normal;
font-style: normal;
font-display: block;
}
*{
padding: 0;
margin: 0;
}
body {
width: 100%;
height: 100%;
position: relative;
background-image: url(hf1.jpg);
background-size: cover;
}
.head {
height: 40px;
background-color: #ffffff;
}
.head .box {
width: 1200px;
height: 40px;
margin: auto;
}
.head .box ul li {
line-height: 40px;
list-style-type: none;
}
.head .box ul li a::after {
float: right;
content: "\e91e";
font-family: 'icomoon';
}
.head .box ul li a{
display: block;
width: 85px;
text-decoration: none;
color: black;
}
.head .box ul li a:hover {
color: coral;
background-color: #eee;
}
.hf {
display: none;
position: absolute;
left: 360px;
width: 600px;
height: 150px;
background-color: #fff;
border-top: none;
}
.hf::after {
content: "\e920";
font-family: 'icomoon';
position: absolute;
top: 35px;
right: 0px;
display: block;
width: 40px;
height: 80px;
font-size: 40px;
line-height: 80px;
background-color: rgba(0, 0, 0, .1);
}
.hf ul {
overflow: hidden;
white-space: nowrap;
width: 550px;
}
.hf ul li {
display: inline-block;
list-style-type: none;
}
.hf ul li img {
width: 150px;
height: 100px;
margin-right: 5px;
margin-top: 5px;
}
.hf ul li img:hover {
border: 2px solid blue;
}
</style>
</head>
<body>
<div class="head">
<div class="box">
<ul>
<li><a href="#">更换皮肤</a></li>
</ul>
</div>
</div>
<div class="hf">
<ul>
<li><img src="hf1.jpg" alt=""></li>
<li><img src="hf2.jpg" alt=""></li>
<li><img src="hf3.jpg" alt=""></li>
<li><img src="hf4.jpg" alt=""></li>
<li><img src="hf5.jpg" alt=""></li>
<li><img src="hf6.jpg" alt=""></li>
<li></li>
<li></li>
</ul>
</div>
<script>
var btn = document.querySelector(".head").querySelector(".box").querySelector("a");
var hf = document.querySelector(".hf");
var img = document.querySelector(".hf").querySelectorAll("img");
console.log(img);
btn.onmouseover = function(){
hf.style.display = 'block';
}
hf.onmouseover = function(){
hf.style.display = 'block';
}
hf.onmouseout = function(){
hf.style.display = 'none';
}
btn.onmouseout = function(){
hf.style.display = 'none';
}
for(var i=0;i<img.length;i++){
img[i].onclick = function(){
document.body.style.backgroundImage = 'url('+this.src+')';
}
}
</script>
</body>
</html>