1. 程式人生 > >html+jquery生成單元格的對角線

html+jquery生成單元格的對角線

<script src="http://code.jquery.com/jquery-latest.js"></script>
<head>
	<style>
		table td {width: 200px; height: 150px; border: 1px solid #000;}
	</style>
</head>
<body onload="change()">
	<table>
		<tr>
			<td class="inline"></td>
		</tr>
	</table>
</body>
<script>
function change() {
	var top = 0;
	var left = 0;
	var length = 0;
	var angle = 0;
	var width = $('.inline').width();
	var height = $('.inline').height();

	//線條position設定為absolute時,座標需要重新定位,獲取單元格的偏移量作為線條的偏移量
	top = $('.inline').offset().top;
	left = $('.inline').offset().left;

	angle = Math.round(Math.atan(width/height)*180/Math.PI);//獲取對角線角度,Math.atan()獲取的是弧度,乘於180/pi得到角度
	length = Math.sqrt(width * width + height * height);//獲取對角線長度,勾股定理

	$('style').append('.inline::before {content: ""; position: absolute; width: 1px;left: ' + left + 'px;top: ' + top + 'px;background-color: #000; transform-origin: top;height: ' + length + 'px; transform: rotate(-' + angle + 'deg);}');
	}
</script>

效果圖