HTML制作一个普通的背景换肤案例2024版

一,完整的代码:

复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>换肤</title>
	<script>
		window.onload = function(){
			var num = 0;
			document.getElementById("d").addEventListener("click",function(){
				num ++;
				console.log(num);
				if((num%2) == 1){
					document.body.style.backgroundColor = "#555";
				}else{
					document.body.style.backgroundColor = "#cecece";
				}
			});
		};
	</script>
	<style>
		.h{
			position: fixed;
			top: 50px;
			right: 50px;
			font-size: 40px;
		}
	</style>
</head>
<body>
	<button id="d" class="h">换肤</button>
</body>
</html>

二,代码讲解:

在页面上使用了一个button按钮标签,分别添加了 id 和 class 选择器方便后续增加样式和事件用处:

运行起来如:

使用Css通过class选择器对button标签进行添加样式:

样式分别添加了 position: fixed; 定位布局,button元素距离浏览器上边框的50像素,在距离浏览器右边框的50像素,并且放大40像素,运行起来如:

接通过js给button按钮添加事件:

首先添加window.onload进行监听元素属性解析后在运行函数的内容,不添加的话会报错。在定义一个变量为num为0方便后续判断,通过document.getElementById获取到button的id属性,并添加点击事件"click",如果触发点击事件则运行后面的函数。当触发一次点击事件时,num就+1,后面进行判断,用num进行取余,如果等于1则给body背景颜色改为:黑色(#000),其他的就为:白色(#fff),运行结果为:

相关推荐
Dem11 分钟前
怎么安装jdk
java·开发语言
wazmlp0018873694 分钟前
python第一次作业
开发语言·python·算法
墨雪不会编程5 分钟前
C++【string篇4】string结尾篇——字符编码表、乱码的来源及深浅拷贝
android·开发语言·c++
咸鱼2.010 分钟前
【java入门到放弃】VUE部分知识点
java·javascript·vue.js
Engineer-Jsp11 分钟前
A problem occurred starting process ‘command ‘bash‘‘
开发语言·bash
weixin_4896900216 分钟前
MicroSIP自定义web拨打协议
服务器·前端·windows
PnZh0Y118 分钟前
python代码练习1
开发语言·python·算法
sheji341619 分钟前
【开题答辩全过程】以 基于python的图书销售数据可视化系统为例,包含答辩的问题和答案
开发语言·python·信息可视化
_Soy_Milk20 分钟前
【算法工程师】—— Python 高级
开发语言·python·算法
程序猿Code21 分钟前
groovy闭包
开发语言·python