【发布时间】:2020-03-22 02:19:23
【问题描述】:
我正在练习 javascript。这里我创建了一个用于动态创建div、a等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