我正在玩JavaScript。我遇到頁面大小調整和動態創建元素位置的問題。父div位於相對位置,附加的子元素相對於添加到的父級是絕對的。當我縮小瀏覽器窗口時,父級可以正常縮放,但兒童的位置不會更新。在現實世界中,你將如何處理這種情況? 謝謝 PS:請記住,我正在努力學習這一點,很多我肯定是錯誤的或不必要的。我也很欣賞這種修正。動態添加絕對定位元素不會與父級流動
<html>
<head>
<!-- <link rel="stylesheet" type="text/css" href="1.css"> -->
<script language="javascript"></script>
<style>
#div1{
\t postion:relative;
\t margin:auto auto;
\t height:400px;
\t width:400px;
\t 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)
{
\t \t obj1 = new child(this,e);
\t }
\t function child(el,e)
\t {
\t \t this.parent = el;
\t \t this.parentID = el.id;
\t \t // Create the object
\t \t this.child = document.createElement('div');
\t \t this.parent.appendChild(this.child);
\t \t // Set some attributes
\t \t var c = this.parent.childElementCount + 1;
\t \t this.child.id = "child"+c;
\t \t // Set some style
\t \t var l = e.clientX - 20;
\t \t var t = e.clientY - 20;
\t \t var stylestring = "position:absolute;top:"+t+"px;left:"+l+"px;height:40px;width:40px;background-color:red;";
\t \t this.child.style.cssText = stylestring;
\t \t // Add some eventhandling
\t \t this.child.addEventListener("click",getchildcoords,false);
\t }
\t function getchildcoords(e)
\t {
\t \t alert(this.id);
\t \t e.stopPropagation();
\t }
</script>
</body>
</html>
您只設置一次位置。如果你想改變位置,你需要使用相對值或者再次設置值(你可以在'window.resize()'事件中做到這一點)。 –
絕對定位對於響應性並不好,因爲它不會自動更新。如果可以的話,我會避免它。如果沒有,你會聽取調整大小的事件並手動更新其位置,這可能會變得非常複雜 –