我创建了一个小表,您可以在其中单击数据单元,这将触发我的Javascript调用函数。此功能在单击的数据单元格的位置显示了一个小“形式”。现在,我添加了一个按钮,该按钮应该隐藏该公式,但是它不起作用,我也不知道为什么。

HTML:

<div id="movableDiv">
<form>
<p>Some text:</p>
<input type="text" name="someText">
<p>A number:</p>
<input type="number" name="aNumber">
<button type="button" ="HideButton">
Hide
</button>
</form>
</div>


CSS:

#movableDiv{
  background-color: lightgrey;
  position: absolute;
  visibility: hidden;
}


Javascript:

document.getElementById("HideButton").onclick = hideDiv;
function hideDiv(){
document.getElementById("movableDiv").style.visibility = "hidden";
}


https://jsfiddle.net/qc1dng63/2/

最佳答案

您的代码中有两个问题:


您用于附加事件侦听器的代码应位于window.onload中。
您的循环应为td.length-1。您可以使用[].forEach.call代替以下代码,而不用编写代码:


//all datacells safed in variablevar datacells = document.getElementsByTagName("td");//length of arrayvar cellsCount = datacells.length;//iterate through arrayfor (var i = 0; i <= cellsCount; i += 1) { //if any of this datacells get clicked, it will call function "example" with id of clicked element as parameter datacells[i].onclick = example;}

下面是更新的代码:



window.onload = function () {
	[].forEach.call(document.getElementsByTagName("td"), function (el) {
		el.onclick = example;
	})

	//if clicked elsewhere, div has to become hidden again.

	//onlick hide, div box becomes hidden again
	document.getElementById("HideButton").onclick = hideDiv;
}

//functions
function example(idOfDatacells) {
	//this references the element, which called the function
	var rect = document.getElementById(this.id).getBoundingClientRect();

	document.getElementById("top").innerHTML = rect.top;
	document.getElementById("left").innerHTML = rect.left;

	var div = document.getElementById("movableDiv");
	div.style.visibility = "visible";
	div.style.top = rect.top + document.getElementById(this.id).clientHeight + "px";
	div.style.left = rect.left + "px";
}

//function for hiding formular
function hideDiv() {
	document.getElementById("movableDiv").style.visibility = "hidden";
}

table {
	width: 100%;
	margin: auto;
	position: relative;
}

td {
	text-align: center;
}

tr:nth-child(2) {
	background-color: lightgrey;
}

tr {
	height: 50px;
}

#movableDiv {
	background-color: lightgrey;
	position: absolute;
	visibility: hidden;
}

<table>
	<tr>
		<th>Header1</th>
		<th>Header2</th>
	</tr>
	<tr>
		<td id="tr1tc1">Data1</td>
		<td id="tr1tc2">Data2</td>
	</tr>
	<tr>
		<td id="tr2tc1">Data3</td>
		<td id="tr2tc2">Data4</td>
	</tr>
</table>
<div id="movableDiv">
	<form>
		<p>Some text:</p>
		<input type="text" name="someText">
		<p>A number:</p>
		<input type="number" name="aNumber">
		<button id="HideButton" type="button">
Hide
</button>
	</form>
</div>
<p id="top">
	Top:
</p>
<p id="left">
	Left:
</p>

10-08 00:06