<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="box" style="position: relative;"></div>
<script>
function Rect(options) {
this.init(options);
}
Rect.prototype = {
// 属性
init: function (options) {
// 父标签
this.parentId = options.parentId;
// 位置
this.left = options.left || 100;
this.top = options.top || 100;
// 自身的属性
this.width = options.width || 200;
this.height = options.height || 100;
this.bgColor = options.bgColor || "red";
this.border = options.border || "none";
this.borderRadius = options.borderRadius || 0;
},
// 行为
render: function () {
// 获取父标签
var parentEle = document.getElementById(this.parentId);
// 创建矩形,添加进父标签里
var rectEle = document.createElement("div");
parentEle.appendChild(rectEle);
// 给矩形定位和添加属性
rectEle.style.position = "absolute";
rectEle.style.left = this.left + "px";
rectEle.style.top = this.top + "px";
rectEle.style.width = this.width + "px";
rectEle.style.height = this.height + "px";
rectEle.style.backgroundColor = this.bgColor;
rectEle.style.border = this.border;
rectEle.style.borderRadius = this.borderRadius + "px";
}
};
// 创建对象
var rect = new Rect({
parentId: "box",
width: 500,
height: 300,
border: "10px solid #000",
borderRadius: 20
});
rect.render();
</script>
</body>
</html>
js面向对象案例:矩形
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。