如何在JavaScript中设置多个CSS样式?

301

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

1
在您的示例中,“allMyStyle”是什么? 在开头,您有一个单个变量列表... - Felix Kling
1
字体大小:12像素;左侧:200像素;顶部:100像素。 - Mircea
1
如果这能够工作,它将是一个包含所有要设置的CSS的字符串:document.getElementById("myElement").style = font-size:12px; left:200px; top:100px - Mircea
有趣的是,似乎按顺序应用多个CSS规则而不是使用cssText方法更快:http://jsperf.com/csstext-vs-multiple-css-rules/4 - Andrei Oniga
或许有用 - undefined
29个回答

0

使用ES6+,您还可以使用反引号,甚至可以直接从某个地方复制CSS:

const $div = document.createElement('div')
$div.innerText = 'HELLO'
$div.style.cssText = `
    background-color: rgb(26, 188, 156);
    width: 100px;
    height: 30px;
    border-radius: 7px;
    text-align: center;
    padding-top: 10px;
    font-weight: bold;
`

document.body.append($div)


0
您可以编写一个函数,逐个设置声明,以避免覆盖任何您没有提供的现有声明。假设您有以下声明的对象参数列表:
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'});


0
请考虑使用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');


0
最干净的解决方案,如在这个答案中建议的,是使用mapjoin Object.entries。 这意味着您可以使用JSON对象编写CSS,这比模板文字更容易管理。
例如:
const el = document.createElement('div')
el.style.cssText = cssObjectToString({
  position: 'absolute',
  top: 0,
  left: 0,
  width: '50px',
  height: '50px',
  background: 'red'
})
document.body.append(el)

function cssObjectToString(styles) { 
  return Object.entries(styles).map(([k, v]) => `${k}:${v}`).join(';')
}

-1
以下 innerHtml 是否有效?

var styleElement = win.document.createElement("STYLE");
styleElement.innerHTML = "#notEditableVatDisplay {display:inline-flex} #editableVatInput,.print-section,i.fa.fa-sort.click-sortable{display : none !important}";


未捕获的引用错误:win 未定义。 - Hexodus

-1
我们可以向Node原型添加样式函数:
Node.prototype.styles=function(obj){ for (var k in obj)    this.style[k] = obj[k];}

然后,只需在任何节点上调用styles方法:

elem.styles({display:'block', zIndex:10, transitionDuration:'1s', left:0});

它将保留任何其他现有的样式并覆盖对象参数中存在的值。


-1
<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>

-2

实现此目标的不同方法:

1. document.getElementById("ID").style.cssText = "display:block; position:relative; font-size:50px";
2. var styles = {"display":"block"; "position":"relative"; "font-size":"50px"};
 
   var obj = document.getElementById("ID");
   Object.assign(obj.style, styles);

3. var obj = document.getElementById("ID");
obj.setAttribute("style", "display:block; position:relative; font-size:50px");

希望这能有所帮助~ RDaksh

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

/

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

2
这与2015年的这个答案相同。 - Quentin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接