單擊鏈接時我有一個HTML頁面&我試圖使一個彈出式元素(僅顯示在鏈接上的div框)出現在單擊的鏈接上方。我使用javascript來做到這一點,但我的問題是彈出式元素位於鏈接下方時,它應該在鏈接上方。使用javascript顯示一種彈出窗口
你知道我在做錯嗎&我該如何解決?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/homepage.dwt" codeOutsideHTMLIsLocked="false" -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<style type="text/css" media="all">
<!--
html, body, div, form, fieldset, legend, label, img { margin: 0; padding: 0; } table { border-collapse: collapse; border-spacing: 0; } th, td { text-align: center; } h1, h2, h3, h4, h5, h6, th, td, caption { font-weight:normal; } img { border: 0; }
body { padding: 20%; background-color: green; }
.container { background-color: white; }
.newEle { width: 100px; height: 100px; background-color: red; }
-->
</style>
<script type="text/javascript">
function getOffset(el)
{
var _x = 0;
var _y = 0;
while(el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop))
{
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.parentNode;
}
return { top: _y, left: _x };
}
function onClick(n, ele)
{
// Should display a popup box just above the HTML element called "ele"
// but what actually happens is that the box is displayed below the element
// called "ele"
var infoBox = document.createElement("div");
infoBox.style.zIndex = "5";
//infoBox.offsetRight = ele.offsetRight;
//infoBox.offsetBottom = parseInt(ele.offsetBottom, 10) - 200 + "px";
infoBox.style.x = getOffset(ele).left + "px";
infoBox.style.y = getOffset(ele).top - 200 + "px";
infoBox.style.width = "200px";
infoBox.style.height = "200px";
infoBox.style.backgroundColor = "blue";
infoBox.innerHTML = "Hello";
document.body.appendChild(infoBox);
}
</script>
</head>
<body>
<div class="container">
<a class="newEle" onclick="onClick(1,this)">Create New Element</a>
</div>
</body>
</html>
這是一個不工作的演示:http://jsfiddle.net/BCFkR/1/。 – Blender 2011-04-01 00:13:35
@Blender,恩,不知道你的意思?就像我說的那樣創建了新的div(popup元素),但它的位置不正確,它應該在鏈接之上,而不是在 – Mack 2011-04-01 00:23:50
之下我做的演示程序不能識別你的'onclick ='處理程序,它是爲什麼它壞了。太懶了修復... – Blender 2011-04-01 01:04:08