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),运行结果为:

相关推荐
nuIl2 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl2 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
AAA大运重卡何师傅(专跑国道)2 小时前
【无标题】
开发语言·c#
nuIl2 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl2 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf2 小时前
Python 异常处理
前端·后端·python
sugar__salt2 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
XBodhi.3 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
MageGojo3 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案
独特的螺狮粉3 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙