CSS3中的javascript layerX和event.layerX转换:translate

时间:2018-06-03 14:41:02

标签: javascript

我把它(红色框)放在中间位置,上下左右,我想得到让位置,目前是负面的,你如何解决?

这是javascript和css以及html:

			var foo = document.getElementsByClassName("div")[0];
			foo.onclick = function(e){
				var ev = window.event || e;
				console.log("is:"+ev.layerX);
			}
			*{
				margin: 0;
				padding: 0;
			}
			html,body{
				background: #CCCCCC;
				width: 100%;
				height: 100%;
			}
			#test{
				position: absolute;
				top:50%;
				left:50%;
				transform: translate(-50%,-50%);
				width:200px;
				height:200px;
				background: red;
			}
			#test .div{
				position: absolute;
				top:0;
				left:0;
				width:200px;
				height:100px;
			}
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>

	</head>
	<body>
		<div id="test">
			<div class="div"></div>
		</div>
	
	</body>
</html>

enter image description here

**为什么离开:-2 -45 ..... ??

我想要(左)有:1 5 3 45 **

1 个答案:

答案 0 :(得分:0)

我认为您需要的是 ev.clientX 。它将给出与窗口相关的位置。如果您想要与 div 相关的位置,则应该减去 div &#39> x

&#13;
&#13;
			var foo = document.getElementsByClassName("div")[0];
			foo.onclick = function(e){
				var ev = window.event || e;
                                var div = ev.target.getBoundingClientRect();
				console.log("is:"+ (ev.clientX - div.left));
			}
&#13;
			*{
				margin: 0;
				padding: 0;
			}
			html,body{
				background: #CCCCCC;
				width: 100%;
				height: 100%;
			}
			#test{
				position: absolute;
				top:50%;
				left:50%;
				transform: translate(-50%,-50%);
				width:200px;
				height:200px;
				background: red;
			}
			#test .div{
				position: absolute;
				top:0;
				left:0;
				width:200px;
				height:100px;
			}
&#13;
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>

	</head>
	<body>
		<div id="test">
			<div class="div"></div>
		</div>
	
	</body>
</html>
&#13;
&#13;
&#13;