换肤效果:点击不同图片,更换相应页面背景
1、定义一组图片,每个src属性赋值背景图片路径
2、获取一组图片元素对象(得到伪数组)
3、for循环给图片绑定点击事件- - -onclick,事件处理程序中设置body元素对象的背景图片为- - -当前被点击的图片的路径
4、注意:body元素对象的获取为- - -document.body,js为背景图片路径赋值注意路径的拼接- - -document.body.style.backgroundImage = ‘url(' + this.src + ‘)';
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title >换肤效果</ title >
< style >
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background: url(images/壁纸1.jpg) no-repeat center top;
background-size: cover;
}
.box {
overflow: hidden;
width: 610px;
margin: 100px auto;
}
.box li {
width: 25%;
height: 100px;
list-style: none;
float: left;
cursor: pointer;
border: 1px solid #fff;
}
img {
width: 100%;
height: 100%;
}
</ style >
</ head >
< body >
< ul class = "box" >
< li >< img src = "images/壁纸1.jpg" alt = "" ></ li >
< li >< img src = "images/壁纸2.jpg" alt = "" ></ li >
< li >< img src = "images/壁纸3.jpg" alt = "" ></ li >
< li >< img src = "images/壁纸4.jpg" alt = "" ></ li >
</ ul >
< script >
var pics = document.querySelector('.box').querySelectorAll('img');
console.log(pics);
for (var i = 0; i < pics.length ; i++) {
pics[i] .onclick = function () {
console.log(this.src);
document.body.style.backgroundImage = 'url(' + this.src + ')';
}
}
</script>
</ body >
</ html >
|
以上就是本文的全部内容,希望对大家的学习有所帮助。