JS實現一個按鈕的方法,JS實現按鈕方法

來源:互聯網
上載者:User

JS實現一個按鈕的方法,JS實現按鈕方法

本文執行個體講述了JS實現一個按鈕的方法。分享給大家供大家參考。具體實現方法如下:

<!doctype html> <html>   <head>     <meta charset="utf-8">     <meta http-equiv="X-UA-Compatible" content="edge">     <script>     window.onload = function(){       var btn = new Btn();       btn.init({width:300});       bindEvent(btn,'show',function(){         alert(1);       })       bindEvent(btn,'click',function(){         alert(2);       })       var oBtn = document.getElementById('btn');       oBtn.onclick = function (){         fireEvent(btn,'show');       }     }       function Btn(){         this.btn= null;         this.settings = {           width:200,           height:40,           borderRadius:6,           text :'按鈕'         };       }       Btn.prototype.init = function (opt){          extend(this.settings,opt);         this.creat();       }       Btn.prototype.creat = function (){         this.btn =document.createElement('div');                  document.body.appendChild(this.btn);         this.btn.innerHTML = this.settings.text;         this.setData();       }       Btn.prototype.destory = function (){         document.body.removeChild(this.btn);       }       Btn.prototype.setData = function (){         this.btn.style.width = this.settings.width +'px';         this.btn.style.height = this.settings.height +'px';         this.btn.style.border ='solid #f00 '+ this.settings.borderRadius +'px';        }     function extend(obj1,obj2){       for(var attr in obj2){         obj1[attr] = obj2[attr];       }     }     function bindEvent(obj,events,fn){       obj.listeners = obj.listeners || {};       obj.listeners[events] = obj.listeners[events] || [];       obj.listeners[events].push( fn );       if(obj.nodeType){         if(obj.addEventListener){           obj.addEventListener(events,fn,false);         }else{           obj.attachEvent('on'+events,fn);         }       }     }     function fireEvent (obj,events){       if(obj.listeners[events]){         for(var i in obj.listeners[events]){           obj.listeners[events][i]();         }       }     }     </script>   </head>   <body>   <a id="btn" style="margin-top: 40px;" >12</a>   </body> </html>

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.