[英]Changing css styling dynamically using javascript
我正在练习 javascript。 这里我创建了一个 JS 类,用于动态创建div
、 a
等网页元素。 下面的代码展示了一个用于创建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 片段:
<div id='root'> </div>
上面的代码成功创建了div
但没有改变css
方法提到的高度和背景颜色。 css
方法应该采用一个具有 css 样式属性及其值的对象并反映更改。 我应该在css
方法或代码中进行哪些更改以使其工作?
更改this.ele.style.keys = props[keys];
to this.ele.style[keys] = props[keys];
keys
是变量,因此您需要使用括号表示法来访问具有变量中名称的道具。 否则,您将尝试访问名为字面keys
的style
的属性。
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' });
<div id='root'> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.