如何找到自动定位的元素的位置?

时间:2019-07-18 19:55:33

标签: javascript html css

我正在尝试制作一个隐藏游戏,您可以在其中在屏幕上移动单词中的一个字母。句子的位置是相对的,但字母的位置是绝对的,因此,如果未设置字母的位置,它将保留在句子中的位置。但我似乎无法使用javascript访问该职位。

window.addEventListener("keydown", hidgame, false);

var vertpos; // = don't know what to put after the variables to get the top and left position.
var horipos; 

function hidgame(event) {
	if (event.keyCode == "38") {
		vertpos--
		document.getElementById("hidgame").style.top = vertpos + "px";
	}
        if (event.keyCode == "40") {
		vertpos++
		document.getElementById("hidgame").style.top = vertpos + "px";
	}
        if (event.keyCode == "37") {
		horipos--
		document.getElementById("hidgame").style.left = horipos + "px";
	}
        if (event.keyCode == "39") {
		horipos++
		document.getElementById("hidgame").style.left = horipos + "px";
	}
#subtitle {
	width: 100%;
	text-align: center;
}

#hidgame {
	position: absolute;
	color: red;
}
<div id="subtitle">Hidden G<span id="hidgame">a</span>&nbsp;&nbsp;me</div> <!--The &nbsp; is only there to fill the space because the span is absolute-->

1 个答案:

答案 0 :(得分:2)

要确定位置,请使用Element.getBoundingClientRect()

此外,考虑将元素存储为变量,而不要反复查找。

window.addEventListener("keydown", hidgame, false);

var letter  = document.getElementById("hidgame");
var vertpos = letter.getBoundingClientRect().top;
var horipos = letter.getBoundingClientRect().left;

function hidgame(event) {
  if      (event.keyCode == "38") vertpos--; //up
  else if (event.keyCode == "40") vertpos++; //down
  else if (event.keyCode == "37") horipos--; //left
  else if (event.keyCode == "39") horipos++; //right

  letter.style.top  = vertpos + "px";
  letter.style.left = horipos + "px";
}
#subtitle {
  width: 100%;
  text-align: center;
}

#hidgame {
  position: absolute;
  color: red;
}
<div id="subtitle">Hidden G<span id="hidgame">a</span>&nbsp;&nbsp;me</div>
<!--The &nbsp; is only there to fill the space because the span is absolute-->