我尝试为元素做一个方法,以便在可能的情况下将元素与父容器对齐(在这个简单版本中需要绝对定位)。这是测试页面:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Align Element</title>
<style>
.jGp_jan {
position:fixed;
background-color:#DDD;
border:2px solid #000;
padding:-1px;
width:320px;
height:auto;
border-radius:6px;
box-shadow:8px 8px 12px black;
}
</style>
<script>
Object.defineProperty(Element.prototype, "align", {
enumerable: false,
configurable: false,
writable: false,
value: function(args) {
var pw = this.parentNode.clientWidth;
var ph = this.parentNode.clientHeight;
var w = this.offsetWidth;
var h = this.offsetHeight;
if(args.indexOf("h")>=0) this.style.left = String(Math.round((pw/2)-(w/2)))+"px";
if(args.indexOf("v")>=0) this.style.top = String(Math.round((ph/2)-(h/2)))+"px";
}
});
function ini(){
document.getElementById("test").align("hv");
}
</script>
</head>
<body onload="ini();">
<div class="jGp_jan" id="jGp_jan_img" style="top:8px; left:8px; width:640px; height:460px;">
<div id="{cabecalho}" style="display:inline; background-color:#666; border-radius:6px; height:22px; position:absolute; top:0px; left:0px; right:0px;">
<button id="{btnFechar}" style="float:left;"> X </button>
<div id="{titulo}" style="float:left; font-weight:bold; color:#FFC;"></div>
<div style="clear:both;"></div>
</div>
<div style="display:inline; position:absolute; top:22px; left:0px; right:0px; bottom:0px;">
<div id="{conteudo}" style="display:block; width:100%; height:100%; overflow:hidden; background-color:#FFF; border-radius:6px;">
<div id="test" style="display:block; position:absolute;"><br />This is a test<br /></div>
</div>
</div>
</div>
</body>
</html>
错误有点神秘:
TypeError: '' is not a function (evaluating 'document.getElementById("test").align("hv")')
我认为有一些细节我不知道......你能看到吗?