我有以下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添加样式类,然后用JavaScript添加该类 classList &简单的add()函数。

style.css

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

JavaScript脚本

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

其他回答

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

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

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

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];
}

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

下面的innerHtml是否有效

var styleElement = win.document.createElement("STYLE"); styleElement。innerHTML = "#notEditableVatDisplay {display:inline-flex} #editableVatInput,.print-section, i.a a.fa-sort. "点击排序{显示:none !重要}";