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

当前回答

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

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

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

其他回答

创建一个函数来处理它,并将参数与你想要更改的样式传递给它。

function setStyle( objId, propertyObject )
{
 var elem = document.getElementById(objId);
 for (var property in propertyObject)
    elem.style[property] = propertyObject[property];
}

像这样叫它

setStyle('myElement', {'fontsize':'12px', 'left':'200px'});

对于propertyObject内部的属性值,您可以使用变量。

强类型的typescript:

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

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

    Object.assign(element.style, newStyle);

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

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

请考虑使用CSS添加样式类,然后用JavaScript添加该类 classList &简单的add()函数。

style.css

.nice-style { 
fontsize : 12px; 
left: 200px;
top: 100px;
}

JavaScript脚本

const addStyle = document.getElementById("myElement"); addStyle.classList.add(“nice-style”);

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

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

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

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

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