使用HTML5制作刻度温度计,让你的网页更生动,更易懂

14 min read

好的,以下是一个简单的HTML5刻度温度计示例代码:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>刻度温度计示例</title>
	<style>
		#thermometer {
			position: relative;
			width: 100px;
			height: 300px;
			background-color: #ccc;
			margin: 50px auto;
			border-radius: 10px;
		}
		#thermometer:before {
			content: "";
			position: absolute;
			top: 0px;
			left: 50%;
			width: 10px;
			height: 25px;
			background-color: #fff;
			margin-left: -5px;
			border-radius: 50%;
			border: 1px solid #000;
		}
		#thermometer:after {
			content: "";
			position: absolute;
			bottom: 0px;
			left: 0px;
			width: 100%;
			height: 50px;
			background-color: #bbb;
			border-bottom-left-radius: 10px;
			border-bottom-right-radius: 10px;
		}
		#thermometer .level {
			position: absolute;
			bottom: 50px;
			left: 0px;
			width: 100%;
			height: 200px;
			background-color: blue;
			border-bottom-left-radius: 10px;
			border-bottom-right-radius: 10px;
			transition: height 0.2s ease;
		}
		#thermometer #temp {
			position: absolute;
			top: 0px;
			left: 0px;
			width: 100%;
			height: 50px;
			text-align: center;
			font-size: 20px;
			font-weight: bold;
			line-height: 50px;
			color: #fff;
		}
		#thermometer input[type="range"] {
			position: absolute;
			top: 50px;
			left: 10%;
			width: 80%;
			height: 200px;
			-webkit-appearance: none;
			background-color: transparent;
			transform: rotate(-90deg);
			transform-origin: 50% 50%;
			cursor: pointer;
		}
		#thermometer input[type="range"]::-webkit-slider-runnable-track {
			background-color: red;
			height: 10px;
			border-radius: 10px;
			border: none;
		}
		#thermometer input[type="range"]::-webkit-slider-thumb {
			background-color: #000;
			width: 25px;
			height: 25px;
			border-radius: 50%;
			border: 1px solid #000;
			-webkit-appearance: none;
			margin-top: -8px;
			cursor: pointer;
		}
	</style>
</head>
<body>
	<div id="thermometer">
		<div id="temp">0℃</div>
		<input type="range" min="-20" max="40" step="1" value="0" oninput="setTemp(this.value)">
		<div class="level" id="level"></div>
	</div>

	<script>
		function setTemp(value) {
			var level = document.getElementById("level");
			level.style.height = ((value + 20) * 5) + "px";
			document.getElementById("temp").innerHTML = value + "℃";
		}
	</script>
</body>
</html>

你可以把代码复制粘贴到您的HTML文件中,并在浏览器中打开查看效果。注意,此代码的刻度范围为-20℃至40℃,可根据需要进行调整。