JavaScript

本笔记为学习网易云课堂上的【撩课-零基础玩转JavaScript】所做。

使用构造函数绘制矩形,可以通过传参改变矩形坐标、宽高、圆角。

思路:

  HTML 创建一个 div ,绑定 id 为 box,之后通过 JS 在该 div 内创建矩形。

  创建矩形构造函数 Rect,在构造函数上写矩形属性,设置矩形属性(左外边距、上外边距、宽、高、背景颜色、圆角、矩形 div 的父 div 的 id)。通过传入参数 options 动态设置矩形属性,参数 options 是一个对象,矩形属性作为 options 对象的键传入。在构造函数的原型对象上写方法,写个绘制矩形的方法,该方法实现创建矩形 div、插入 div、绑定样式属性。实例化构造函数。

代码:

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="utf-8">
 5         <title></title>
 6     </head>
 7     <body>
 8         <div id="box"></div>
 9         <script>
10             //矩形的构造函数
11             function Rect(options){
12                 options = options || {},
13                 this.parentId = options.parentId || 'box';
14                 this.width = options.width || 100;
15                 this.height = options.height || 100;
16                 this.left = options.left || 100;
17                 this.top = options.right || 100;
18                 this.bgColor = options.bgColor || '#ccc';
19                 this.radius = options.radius || 0;
20             }
21             //矩形的原型对象
22             Rect.prototype = {
23                 constructor: Rect,
24                 //绘制
25                 render: function(){
26                     //创建 div
27                     var divE = document.createElement('div');
28                     var fatherE = document.getElementById(this.parentId);
29                     fatherE.appendChild(divE);
30                     //让矩形 div 相对 父 div 定位
31                     fatherE.style.position = 'relative';
32                     divE.style.position = 'absolute';
33                     //绑定样式属性
34                     divE.style.width = this.width + 'px';
35                     divE.style.height = this.height + 'px';
36                     divE.style.left = this.left + 'px';
37                     divE.style.top = this.top + 'px';
38                     divE.style.backgroundColor = this.bgColor;
39                     divE.style.borderRadius = this.radius;
40                 }
41             }
42             //传入参数
43             var options = {
44                 parentId: 'box',
45                  200,
46                 height: 200,
47                 bgColor: 'red',
48                 radius: '20%'
49             }
50             //创建实例
51             var rect1 = new Rect(options).render();
52         </script>
53     </body>
54 </html>

效果:

原文地址:https://www.cnblogs.com/xiaoxuStudy/p/15073934.html