6

我想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';
}

这是我的相关 html 代码

<input type="submit" name="cssandcreate" id="cssandcreate" value="css"  onclick="css();"/>
4

3 回答 3

7

The left, and top CSS style settings aren't working because you must first set the position property. If the position property is not set, setting the left and top styles will have no affect. The position property has these settings:

  • static
  • absolute
  • fixed
  • relative
  • initial
  • inherit

So, try setting the position property before setting left and top:

object.style.position="absolute"

The differences between the position properties affect how subsequent settings position your elements.

于 2014-02-23T22:04:31.033 回答
1
document.getElementById('someID').style.position='absolute';
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';

根据 Sandy Good 的建议,我将第一行代码添加到您的代码中。他说在使用“左”和“上”参数之前简单地设置“位置”参数。所以我做了。它有效!

于 2014-04-16T18:38:02.027 回答
1

我希望这是你正在寻找的:

function css(){
    var element = document.createElement('div');
    element.className = "someID";
    document.body.appendChild(element);        
    element.appendChild(document.createTextNode
     ('hello this is javascript work'));

    // this properties are work
    var a = document.getElementsByClassName('someID');

    for(var i in a ){
        a[i].style.zIndex='3';
        a[i].style.color='rgb(255,255,0)';
        a[i].style.background='rgb(0,102,153)';
        a[i].style.width='700px';
        a[i].style.height='200px';
        a[i].style.left='500px';
        a[i].style.top='90px';
    }
}
于 2013-10-29T05:01:58.330 回答