【问题标题】:Is it possible to store style properties in a js array?是否可以将样式属性存储在 js 数组中?
【发布时间】:2016-08-28 08:26:08
【问题描述】:

我创建了一堆样式属性,我想使用 for 循环将它们添加到 div 元素。我不知道我的语法有什么问题:

function createShot(){

var shot = new shotConstructor(spaceship.x,(765-(spaceship.y+15)),15,15,"#000000","","","","","","");
var createDiv = document.createElement("div");
var AddId = createDiv.setAttribute("id","shot");
var element = document.getElementById("dv_grid");
var append = element.appendChild(createDiv);
var shotStyle=document.getElementById('shot').style;
var style=[width=shot.w+"px",height=shot.h+"px",left=shot.x+"px",top=shot.y+"px",backgroundColor="#000000",position="absolute"];

for(i=0;i<6;i++){
    shotStyle+style[i];

}

【问题讨论】:

  • 缺少一个 } 来关闭初学者的 for 循环。
  • shotStyle+style[i]; 什么都不做
  • 那我该怎么办?

标签: javascript arrays styles


【解决方案1】:
[width=shot.w+"px"]
 ^^^^^

这是一个全局变量。

[width=shot.w+"px"]
       ^^^^^^^^^^^

这是您分配给全局变量的值。

然后将值放在数组中。

这为您提供了一组样式属性值,这些值与任何属性名称无关。


shotStyle+style[i];

这会将 CSSStyleDeclaration 转换为字符串,将样式属性值(不要记住属性名称!)附加到该字符串,然后丢弃结果(因为您没有在任何地方分配它)。


您需要将属性名称与值一起存储。由于顺序无关紧要,因此您应该使用对象而不是数组来做到这一点。

var style = {
    width: shot.w + "px",
    height: shot.h + "px",
    left: shot.x + "px",
    top: shot.y + "px",
    backgroundColor: "#000000",
    position: "absolute"
};

然后您需要适当的语法来循环对象并使用每个属性的名称和值。

for (var prop in style) {
    shotStyle[prop] = style[prop];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多