浅谈JavaScript DOM绘制柱状图

本文介绍了一种使用纯JavaScript和DOM操作来绘制简单柱状图的方法。通过动态创建和定位HTML元素,实现了数据的可视化展示。文章包含了完整的HTML和JavaScript代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
	<head>
		<title>JavaScript DOM绘制柱状图</title>
		<style>
			#chart-wrap{ 
				width:910px; 
				height:240px;
				border:solid 1px #B3B3DC;
				position:relative; 
				top:40px; 
				left:20px;
			} 
		</style>
	</head>
	<body>
		<div id="chart-wrap"></div>
		<script>
			function renderChart(data) {
				var cw = document.getElementById("chart-wrap"); 
				cw.innerHTML = ""; 
				var max = 0; 
				for (var index in data) {
					if (data[index] > max)
						max = data[index];
				}
				var percent = 180 / max; 
				var i = 0;
				for (var index in data) { 
					var bar = document.createElement("div"); 
					bar.id = index + "_" + data[index]; 
					bar.style.height = Math.round(percent * data[index]) + "px"; 
					bar.style.width = "40px";
					bar.style.left = (i * 40) + 165 + "px"; 
					bar.style.marginLeft = (i * 20) + "px"; 
					bar.style.position = "absolute"; 
					bar.style.background = "none repeat scroll 0 0 pink";
					bar.style.overflow = "hidden";
					bar.setAttribute("title", index + ":" + data[index]);
					bar.style.display = "block"; 
					bar.style.top = 200 - Math.round(percent * data[index]) + "px"; 
					cw.appendChild(bar); 
					var axis = document.createElement("div"); 
					axis.id = "axis_" + i; 
					axis.style.width = "40px"; 
					axis.style.left = (i * 40) + 165 + "px"; 
					axis.style.marginLeft = (i * 20) + "px";
					axis.style.textAlign = "center"; 
					axis.style.position = "absolute"; 
					axis.style.top = "205px"; 
					axis.innerHTML = '<span style="font-size:12px; color:grey;"> ' + i + '</span>'; 
					cw.appendChild(axis); 
					i++;
				} 	
				for (var i = 0; i < 5; i++) { 
					var ayis = document.createElement("div");  
					ayis.style.width = "30px"; 
					ayis.style.position = "absolute"; 
					ayis.style.top = (36 * i) + (20 - 6) + "px"; 
					ayis.style.left = "140px"; 
					ayis.innerHTML = '<span style="font-size:12px; color:grey;"> ' + Math.round(max - (max / 5) * i) + '</span>'; 
					cw.appendChild(ayis); 
					var line = document.createElement("div"); 
					line.setAttribute("style", "width:580px; left:165px; border-top:1px dotted grey; height:1px; line-height:1px; display:block; overflow:hidden; position:absolute; "); 
					line.style.top = (36 * i) + 20 + "px"; 
					cw.appendChild(line); 
				} 
			}
			var data = [10,60,50,30,40,80,20,70,100,90];
			renderChart(data);
		</script>
	</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值