需求
封装一个类,可以动态地创建节点,
标签节点该有的样式和属性它都有,可以追加到页面中
要点
运用面向对象的思想,把需求分为四个部分
1,节点创建
2.设置样式
3.设置属性
4.节点追加
把它们作为类方法进行定义即可
代码实现
<div id="app">
<!-- <img src="../../Pictures/IMG114413.jpg"> -->
</div>
<script>
class CreateTag {
constructor(tag, styleObj, attrObj, parent) {
// 这些this不能漏掉
this.tagObj = document.createElement(tag);
this.styleObj = styleObj;
this.attrObj = attrObj;
this.parent = parent;
this.setStyle();
this.setAttr();
this.appendTag();
}
setStyle() {
Object.assign(this.tagObj.style, this.styleObj);//深拷贝
}
setAttr() {
Object.assign(this.tagObj, this.attrObj);
}
appendTag() {
this.parent.appendChild(this.tagObj);//追加
}
}
let ct1 = new CreateTag("img", {
width: "400px",
height: "300px"
}, {
src: '../../Pictures/IMG114413.jpg'
}, document.getElementById("app"));//把img追加到app下
</script>
这篇博客介绍了如何运用面向对象编程思想,封装一个名为`CreateTag`的类来动态创建HTML节点。该类包含四个核心方法:节点创建、设置样式、设置属性和节点追加。通过实例化`CreateTag`类并传入相应参数,可以轻松将一个img节点添加到指定的父元素下,并设置其样式和属性。示例中展示了如何创建一个img节点并将其添加到id为'app'的div元素内。
10万+

被折叠的 条评论
为什么被折叠?



