给按钮设置点击事件监听,点击按钮更换皮肤
html代码
<style>
* {
margin: 0;
padding: 0;
}
body {
width: 100vw;
height: 100vh;
/* 添加图片 */
background-color: url(./img/p1.jpg);
/* 背景不重复 */
background-repeat: no-repeat;
/* 背景覆盖 */
background-size: cover;
}
</style>
<body>
<button>皮肤1</button>
<button>皮肤2</button>
<button>皮肤3</button>
</body>
js代码
<script>
// 绑定选择器
let butt = document.querySelectorAll("button");
let body = document.querySelector("body");
// 获取图片保存
let url = ["url(./img/p1.jpg)","url(./img/p2.jpg)","url(./img/p3.jpg)"]
for (let i = 0; i < butt.length; i++) {
//设置点击事件
butt[i].onclick = function () {
body.style.backgroundImage = url[i];
}
}
</script>
效果图