我有以下JavaScript变量:

var fontsize = "12px"
var left= "200px"
var top= "100px"

我知道我可以像这样迭代地将它们设置为我的元素:

document.getElementById("myElement").style.top=top
document.getElementById("myElement").style.left=left

有没有可能把它们都放在一起,就像这样?

document.getElementById("myElement").style = allMyStyle 

当前回答

您可以编写一个函数,将声明单独设置,以免覆盖您没有提供的任何现有声明。假设你有这个对象参数声明列表:

const myStyles = {
  'background-color': 'magenta',
  'border': '10px dotted cyan',
  'border-radius': '5px',
  'box-sizing': 'border-box',
  'color': 'yellow',
  'display': 'inline-block',
  'font-family': 'monospace',
  'font-size': '20px',
  'margin': '1em',
  'padding': '1em'
};

你可以写一个这样的函数:

function applyStyles (el, styles) {
  for (const prop in styles) {
    el.style.setProperty(prop, styles[prop]);
  }
};

它接受一个元素和一个样式声明的对象属性列表,以应用于该对象。下面是一个用法示例:

const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);

applyStyles(p, myStyles);
applyStyles(document.body, {'background-color': 'grey'});

// styles to apply const myStyles = { 'background-color': 'magenta', 'border': '10px dotted cyan', 'border-radius': '5px', 'box-sizing': 'border-box', 'color': 'yellow', 'display': 'inline-block', 'font-family': 'monospace', 'font-size': '20px', 'margin': '1em', 'padding': '1em' }; function applyStyles (el, styles) { for (const prop in styles) { el.style.setProperty(prop, styles[prop]); } }; // create example paragraph and append it to the page body const p = document.createElement('p'); p.textContent = 'This is a paragraph.'; document.body.appendChild(p); // when the paragraph is clicked, call the function, providing the // paragraph and myStyles object as arguments p.onclick = (ev) => { applyStyles(p, myStyles); } // this time, target the page body and supply an object literal applyStyles(document.body, {'background-color': 'grey'});

其他回答

var styles = {
    "background-color": "lightgray",
    "width": "500px",
    "height": "300px"
};

/

var obj = document.getElementById("container");
Object.assign(obj.style, styles);

我只是无意中来到这里,我不明白为什么需要这么多代码来实现这一点。

使用字符串插值添加CSS代码。

Let styles = ' 字体大小:15他们; 颜色:红色; 变换:旋转(20度) document.querySelector(“*”)。样式=样式 一个

使用ES6+,你也可以使用反引号,甚至直接从某个地方复制css:

const $div = document.createElement('div') 美元的div。innerText = 'HELLO' div.style美元。cssText = ' Background-color: rgb(26, 188, 156); 宽度:100 px; 高度:30 px; border - radius: 7 px; text-align:中心; padding-top: 10 px; 粗细:大胆的; ` document.body.append (div)美元

这是一个老问题,但我认为对于那些不想覆盖先前声明的样式的人来说,使用一个函数可能是值得的。下面的函数仍然使用Object。赋值以正确地固定样式。以下是我所做的

function cssFormat(cssText){

   let cssObj = cssText.split(";");
   let css = {};
   
   cssObj.forEach( style => {

       prop = style.split(":");

       if(prop.length == 2){
           css[prop[0]].trim() = prop[1].trim();
       } 

   }) 
   
  return css;
}

现在你可以这样做

let mycssText = "background-color:red; color:white;";
let element = document.querySelector("body");

Object.assign(element.style, cssFormat(mycssText));

您可以通过向函数中同时提供元素选择器和文本来简化这一点,这样就不必使用Object了。每次都要分配。例如

function cssFormat(selector, cssText){
  
   let cssObj = cssText.split(";");
   let css = {};
   
   cssObj.forEach( style => {

       prop = style.split(":");

       if(prop.length == 2){
           css[prop[0]].trim() = prop[1].trim();
       } 

   }) 

   element = document.querySelector(selector);
   
   Object.assign(element.style, css); // css, from previous code

} 

现在你可以做:

cssFormat('body', 'background-color: red; color:white;') ;

//or same as above (another sample) 
cssFormat('body', 'backgroundColor: red; color:white;') ; 

注意:在选择之前,请确保您的文档或目标元素(例如,body)已经加载。

<button onclick="hello()">Click!</button>

<p id="demo" style="background: black; color: aliceblue;">
  hello!!!
</p>

<script>
  function hello()
  {
    (document.getElementById("demo").style.cssText =
      "font-size: 40px; background: #f00; text-align: center;")
  }
</script>