js如何写组件

2025-10-29 21:09:33

1、新建一个测试页秤狠墨面,用来测试js封装组件代码,这里添加三个div块,后面会使用封装的组件代码来操作这三个块

<body>

测试Js封装组件

<div class="test1" onclick="myComponent.changeColor(this,'#41c30d');">测试块1</div>

<div class="test2" onclick="myComponent.changeColor(this,'#c30505');">测试块2</div>

<div class="test3" onclick="myComponent.hide(this);">点击隐藏</div>

</body>

js如何写组件

2、为了演示测试效果,分别给三个块添加不同的样式

<style type="text/css">

.test1{

   background-color: #c39729;

   width: 100px;

   height: 100px;

}

.test2{

   background-color: #2315c3;

   color: red;

   width: 100px;

   height: 100px;

}

.test3{

   background-color: #c30505;

   color: red;

   width: 100px;

   height: 100px;

}

</style>

js如何写组件

3、重点的地方是js组件的封装,这里只是简单的演示组件的封装,结构一样,内容就写了简单的2个测试方法,在正常发封装组件中,在组件方法里可以添加N个方法

<script>

(function(window, undefined) {

   //将组件的方法封装在一个类中

   function myComponent() {

   }

   myComponent.prototype = {

    //这里可以添加组件方法

       changeColor: function(that, color){

        that.style.background = color;

       },

       hide:function(that){

        that.style.display = 'none';

       }

   };

   //将组件绑定到window对象上

   window.myComponent = window.myComponent || new myComponent();

})(window);

</script>

这里添加了2个方法,一个是changeColor方法,一个是hide方法,后续需要封装的方法,都写在这里。

js如何写组件

4、打开浏览器开场腊始测试页面效果,默认打开如图显示3个div色块

js如何写组件

5、点击测试块1和测试块2,颜色分别变化了。表示上面封装的方法是正常可以使用的

js如何写组件

6、点击隐藏测试块,测试hide方法是否可以正常使用。点击之后,色块正常隐藏了。到此js的组件封装方法演示完成。后面如果需要编写自己的封装组件,只需要将上面演示的js组件代码复制,在添加方法区域添加自己的方法即可。

js如何写组件

7、完整的测试代码如下:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<style type="text/css">

.test1{

   background-color: #c39729;

   width: 100px;

   height: 100px;

}

.test2{

   background-color: #2315c3;

   color: red;

   width: 100px;

   height: 100px;

}

.test3{

   background-color: #c30505;

   color: red;

   width: 100px;

   height: 100px;

}

</style>

<script>

(function(window, undefined) {

   //将组件扯裹的方法封装在一个类中

   function myComponent() {

   }

   myComponent.prototype = {

    //这里可以添加组件方法

       changeColor: function(that, color){

        that.style.background = color;

       },

       hide:function(that){

        that.style.display = 'none';

       }

   };

   //将组件绑定到window对象上

   window.myComponent = window.myComponent || new myComponent();

})(window);

</script>

</head>

<body>

测试Js封装组件

<div class="test1" onclick="myComponent.changeColor(this,'#41c30d');">测试块1</div>

<div class="test2" onclick="myComponent.changeColor(this,'#c30505');">测试块2</div>

<div class="test3" onclick="myComponent.hide(this);">点击隐藏</div>

</body>

</html>

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢