我正在玩JavaScript。我遇到了页面大小调整和动态创建元素位置的问题。 Parent div位于相对位置,附加的子元素相对于它们添加到的父级是绝对的。当我缩小浏览器窗口时,父级可以缩放,但子级的位置不会更新。你会如何在现实世界中处理这样的情况? 谢谢 PS:请记住,我正在努力学习这一点,而且我确定错误或不必要。我也很欣赏这种修正。
<html>
<head>
<!-- <link rel="stylesheet" type="text/css" href="1.css"> -->
<script language="javascript"></script>
<style>
#div1{
postion:relative;
margin:auto auto;
height:400px;
width:400px;
background-color: black;
}
</style>
</head>
<body>
<!-- Goal; -->
<!-- I want a js class that will create itself and manage its own properties
So when I click on the div I fire up a new object button. -->
<div>
<label id = "lblID"></label>
<div id="div1"></div>
</div>
<script>
document.getElementById("div1").addEventListener("click", createchild, false);
function createchild(e)
{
obj1 = new child(this,e);
}
function child(el,e)
{
this.parent = el;
this.parentID = el.id;
// Create the object
this.child = document.createElement('div');
this.parent.appendChild(this.child);
// Set some attributes
var c = this.parent.childElementCount + 1;
this.child.id = "child"+c;
// Set some style
var l = e.clientX - 20;
var t = e.clientY - 20;
var stylestring = "position:absolute;top:"+t+"px;left:"+l+"px;height:40px;width:40px;background-color:red;";
this.child.style.cssText = stylestring;
// Add some eventhandling
this.child.addEventListener("click",getchildcoords,false);
}
function getchildcoords(e)
{
alert(this.id);
e.stopPropagation();
}
</script>
</body>
</html>
&#13;
答案 0 :(得分:0)
<html>
<head>
<!-- <link rel="stylesheet" type="text/css" href="1.css"> -->
<script language="javascript"></script>
<style>
#div1{
position:relative;
margin:auto auto;
height:400px;
width:400px;
background-color: black;
}
</style>
</head>
<body>
<!-- Goal; -->
<!-- I want a js class that will create itself and manage its own properties
So when I click on the div I fire up a new object button. -->
<div>
<label id = "lblID"></label>
<div id="div1"></div>
</div>
<script>
document.getElementById("div1").addEventListener("click", createchild, false);
function createchild(e)
{
obj1 = new child(this,e);
}
function child(el,e)
{
this.parent = el;
this.parentID = el.id;
// Create the object
this.child = document.createElement('div');
// Set some attributes
var c = this.parent.childElementCount + 1;
this.child.id = "child"+c;
// Set some style
var l = e.offsetX - 20;
var t = e.offsetY - 20;
var stylestring = "position:absolute;top:"+t+"px;left:"+l+"px;height:40px;width:40px;background-color:red;";
this.child.style.cssText = stylestring;
el.appendChild(this.child);
// Add some eventhandling
this.child.addEventListener("click",getchildcoords,false);
}
function getchildcoords(e)
{
alert(this.id);
e.stopPropagation();
}
</script>
</body>
</html>
&#13;