簡體   English   中英

將樣式對象應用於DOM元素

[英]apply object of style to DOM element

我知道我們可以使用.style將CSS應用於DOM元素,如下所示:

document.getElementById("test").style.color="red";

我想知道,是否可以應用樣式對象,如下所示:

newStyle: {
  position : 'fixed';
  width : '300px';
  height : '20px';
  top : '0';
}

如何通過使用.style來應用newStyle ,這可能嗎? (我們這里不使用jQuery)

您可以使用Object.assign

Object.assign(myElement.style, {
  width: '300px',
  height: '20px'
});

 Object.assign(document.getElementById("test").style, { position: 'fixed', width: '300px', height: '100px', top: '0' }); 
 <div id="test" style="background: green"></div> 

您可以通過以下方式遍歷樣式的屬性:

  var newStyle = {
  position : 'fixed',
  width : '300px',
  height : '20px',
  top : '0'
};

for (i in newStyle)
  document.getElementById("test").style[i] = newStyle[i];

嘗試這個:

 var mystyle = { color: 'red' }; for (var property in mystyle) { if (mystyle.hasOwnProperty(property)) { document.getElementById("updateStyle").style[property] = mystyle[property]; } } 
 <p id="updateStyle">Hi This is demo text.</p> 

用您自己的ID替換updateStyle

按規則應用是不好的。 它使瀏覽器重新渲染多次。 您可以一次性使用所有更改-通過使用cssText

因此,根據您的情況,您需要將對象轉換為字符串,然后一次性應用所有樣式:

var newStyle = {
  position: 'fixed',
  width: '300px',
  height: '20px',
  top: '0'
}

var styles = [];
for(var rule in newStyle) styles.push(rule+': '+newStyle[rule]);

document.getElementById("test").style.cssText = styles.join(';');

您可以擴展“ HTMLElement ”的原型。 添加一種方法來遍歷包含樣式信息的對象。 您可以這樣做:

HTMLElement.prototype.applyStyleObject = function (styleObject) {
  for (var item in this.style) {

    var objProp = styleObject[item];

    if (objProp !== undefined) {
      this.style[item] = objProp;
    }

  }
}

我已經完成了第一個原型作為示例,說明如何在野外使用它:):

 //The object containing the style elements var obj = { width: "200px", height: "100px" } var spanobj = { color: "red" } //Cached the div node var divNode = document.getElementById("div"); //Extend the HTMLElement prototype HTMLElement.prototype.applyStyleObject = function (styleObject) { for (var item in this.style) { var objProp = styleObject[item]; if (objProp !== undefined) { this.style[item] = objProp; } } } //Execute the new method divNode.applyStyleObject(obj); document.getElementById("span").applyStyleObject(spanobj); document.getElementsByTagName("figure")[0].applyStyleObject(obj); 
 div { border: solid 1px black; } figure { border: solid 1px black; } 
 <div id="div"></div> <span id="span">This is a span tag</span> <figure></figure> 

如果您擴展了javascript對象的原型 ,則該對象將應用於該對象的所有新創建的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM