Mad*_*tha 6 html javascript css position
我想div手动创建一个元素,然后使用JavaScript为它添加一些CSS样式.我创建了一个div元素并用JavaScript改变了它的风格.问题是,一些CSS样式不起作用.
(color,background,width,height)这些属性的工作不错,但(zIndex,top,left)性能不工作.我想知道为什么会发生这种情况以及如何纠正它.
这是我的JavaScript代码:
function css()
{
var element = document.createElement('div');
element.id = "someID";
document.body.appendChild(element);
element.appendChild(document.createTextNode
('hello this javascript works'));
// these properties work
document.getElementById('someID').style.zIndex='3';
document.getElementById('someID').style.color='rgb(255,255,0)';
document.getElementById('someID').style.background='rgb(0,102,153)';
document.getElementById('someID').style.width='700px';
document.getElementById('someID').style.height='200px';
//these do not work
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';
}
Run Code Online (Sandbox Code Playgroud)
这是我的相关HTML代码
<input type="submit" name="cssandcreate" id="cssandcreate" value="css" onclick="css();"/>
Run Code Online (Sandbox Code Playgroud)
在left和topCSS样式设置不工作,因为你必须先设置position属性.如果position未设置该属性,则设置left和top样式将不起作用.该position属性具有以下设置:
因此,请position在设置之前尝试设置属性left并top:
object.style.position="absolute"
Run Code Online (Sandbox Code Playgroud)
position属性之间的差异会影响后续设置如何定位元素.