【问题标题】:Adding element with a specific style using appendchild method使用 appendchild 方法添加具有特定样式的元素
【发布时间】:2013-07-06 23:33:33
【问题描述】:

这是我的代码:

(a=document).getElementsByTagName('body')[0].appendChild(a.createElement('div').style.cssText="someCssStyle");

它不起作用! 但是当我只写这个时:

(a=document).getElementsByTagName('body')[0].appendChild(a.createElement('div'));

它有效,为什么我不能添加具有特定样式的 div 元素? 我的工作有什么问题? 我想添加一个具有特定样式的 div 元素,只需使用 chrome 上的 URL 植入:

javascript://all of my code goes here

所以它一定很短。

【问题讨论】:

    标签: javascript css dom appendchild createelement


    【解决方案1】:

    它不起作用的原因是在这里:

    ...appendChild(a.createElement('div').style.cssText="someCssStyle")
    

    您将字符串 ("someCssStyle") 传递给appendChild,而不是元素引用。 JavaScript 中赋值的结果是右手边的值。

    我不推荐,但你可以使用the comma operator 这样做:

    (a=document).getElementsByTagName('body')[0].appendChild(d=a.createElement('div'),d.style.cssText="someCssStyle",d);
    

    请注意,您的代码和上面的代码都成为The Horror of Implicit Globals 的牺牲品。

    或者更合理的,一个函数:

    (function(){var a=document,d=document.createElement('div');d.style.cssText="someCssStyle";a.getElementsByTagName('body')[0].appendChild(d)})();
    

    ...其中不会成为THoIG的牺牲品。

    【讨论】:

    • 样式代码也一样吧? d.style.cssText="height:100px,width:50px" 但不是 d.style.cssText="height:100px;width:50px"
    • @user1283226:不,样式用; 分隔,而不是,。逗号运算符是 JavaScript 的东西。
    • 好的,所以代码不起作用,因为我有太多样式要应用我想我会在添加 div 之前添加样式,就像你的第三个代码一样,但直接没有功能,非常感谢先生
    • @user1283226:你需要这个功能。否则,您正在向页面添加/覆盖全局变量,这是一个非常糟糕的主意(tm)。 :-)(特别是如果他们是 ad。)请参阅(在 JavaScript 控制台中查看):jsbin.com/enicag/1 (source]。
    【解决方案2】:

    a.createElement('div').style.cssText="someCssStyle"

    这将返回“someCssStyle”作为(a=document).getElementsByTagName('body')[0].appendChild( 函数的参数。所以 div 永远不会被添加。你能看出这里的问题吗?

    您必须创建 div,设置样式,然后将其添加到正文中。像这样

    var div = document.createElement("div");
    div.style.cssText = "someCssStyle";
    
    document.body.appendChild(div);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 2014-05-16
      • 2014-03-28
      • 2013-10-14
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      相关资源
      最近更新 更多