我有以下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 

当前回答

对我来说最简单的方法就是使用字符串/模板字面值:

elementName.style.cssText = `
                                width:80%;
                                margin: 2vh auto;
                                background-color: rgba(5,5,5,0.9);
                                box-shadow: 15px 15px 200px black; `;

伟大的选择,因为你可以使用多行字符串,使生活更容易。

查看字符串/模板文字在这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

其他回答

JavaScript库允许您非常轻松地完成这些工作

jQuery

$('#myElement').css({
  font-size: '12px',
  left: '200px',
  top: '100px'
});

对象和for-in循环

或者,一个更优雅的方法是一个基本对象& for循环

var el = document.getElementById('#myElement'),
    css = {
      font-size: '12px',
      left: '200px',
      top: '100px'
    };  

for(i in css){
   el.style[i] = css[i];
}

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

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'});

这是一个老问题,但我认为对于那些不想覆盖先前声明的样式的人来说,使用一个函数可能是值得的。下面的函数仍然使用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)已经加载。

因为字符串支持添加,你可以很容易地添加你的新样式,而不需要覆盖当前的样式:

document.getElementById("myElement").style.cssText += `
   font-size: 12px;
   left: 200px;
   top: 100px;
`;

强类型的typescript:

对象。Assign方法很好,但是使用typescript你可以像这样自动完成:

    const newStyle: Partial<CSSStyleDeclaration> =
    { 
        placeSelf: 'centered centered',
        margin: '2em',
        border: '2px solid hotpink'
    };

    Object.assign(element.style, newStyle);

注意属性名是驼峰形的,没有破折号。

这甚至会告诉你它们何时被弃用。