【问题标题】:Changing css styling dynamically using javascript使用 javascript 动态更改 css 样式
【发布时间】:2020-03-22 02:19:23
【问题描述】:

我正在练习 javascript。这里我创建了一个用于动态创建diva等Web元素的JS类。下面的代码展示了一个用于创建div元素的类:

class DivBlock {

 //creates the div element
 constructor(id) {
   this.ele = document.createElement('div');
   this.ele.id = id;
   this.ele.style.height = '100px';
   this.ele.style.width = '200px';
   this.ele.style.border = '1px solid black';
 }

 // sets the css properties
 css(props) {
   var keyslist = Object.keys(props);
   console.log(keyslist);
   console.log(props);
   var style = keyslist.map((keys) => {
     this.ele.style.keys = props[keys];
     return this.ele.style.keys;
   });
   console.log(style);
 }

 getId() {
   return this.ele.id;
 }

 getNode() {
   return this.ele;
 }

 //adds the div-element to the parent element/tag
 mount(parent_id) {
   document.getElementById(parent_id).appendChild(this.ele);
 }

}

var d = new DivBlock('root-div');
d.mount('root') //passing parent tag id
d.css({
 height: '500px',
 backgroundColor: 'red'
});

Html sn-p:

<div id='root'> </div>

上面的代码成功地创建了div,但没有像css 方法中提到的那样改变高度和背景颜色。 css 方法应采用具有 css 样式属性及其值的对象并反映更改。我应该在css 方法或代码中进行哪些更改才能使其正常工作?

【问题讨论】:

    标签: javascript html css dom dom-manipulation


    【解决方案1】:

    this.ele.style.keys = props[keys]; 更改为this.ele.style[keys] = props[keys];

    keys 是变量,因此您需要使用方括号表示法来访问具有变量中名称的道具。否则,您将尝试访问 style 的属性,字面意思是 keys


    class DivBlock {
    
      //creates the div element
      constructor(id) {
        this.ele = document.createElement('div');
        this.ele.id = id;
        this.ele.style.height = '100px';
        this.ele.style.width = '200px';
        this.ele.style.border = '1px solid black';
      }
    
      // sets the css properties
      css(props) {
        var keyslist = Object.keys(props);
        console.log(keyslist);
        console.log(props);
        var style = keyslist.map((keys) => {
          this.ele.style[keys] = props[keys];
          return this.ele.style[keys];
        });
        console.log(style);
      }
    
      getId() {
        return this.ele.id;
      }
    
      getNode() {
        return this.ele;
      }
    
      //adds the div-element to the parent element/tag
      mount(parent_id) {
        document.getElementById(parent_id).appendChild(this.ele);
      }
    
    }
    
    var d = new DivBlock('root-div');
    d.mount('root') //passing parent tag id
    d.css({
      height: '500px',
      backgroundColor: 'red'
    });
    &lt;div id='root'&gt; &lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 2019-08-18
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2017-07-18
      相关资源
      最近更新 更多