制作一个JavaScript温度计可以通过HTML、CSS和JavaScript来实现。这个温度计可以显示当前的温度值,并且可以根据需要动态更新。以下是一个简单的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript温度计</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="thermometer">
<div class="temperature" id="temperature">0°C</div>
</div>
<button onclick="updateTemperature()">更新温度</button>
<script src="script.js"></script>
</body>
</html>
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #f0f0f0;
}
.thermometer {
width: 200px;
height: 400px;
background-color: #fff;
border: 2px solid #000;
position: relative;
overflow: hidden;
}
.temperature {
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
font-size: 2em;
color: #000;
}
function updateTemperature() {
// 模拟获取当前温度(实际应用中可以从服务器获取或使用传感器数据)
const currentTemperature = Math.floor(Math.random() * 40); // 随机生成0到39之间的温度
document.getElementById('temperature').textContent = `${currentTemperature}°C`;
// 更新温度计的视觉效果
const tempElement = document.querySelector('.temperature');
tempElement.style.height = `${currentTemperature * 10}px`; // 每度对应10px的高度
}
div
和一个按钮用于更新温度。updateTemperature
,用于更新温度值并调整温度计的高度以反映当前温度。requestAnimationFrame
来优化动画效果,减少不必要的重绘。通过这种方式,你可以创建一个简单的JavaScript温度计,根据具体需求进一步扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云