>  기사  >  웹 프론트엔드  >  JS_javascript 스킬로 버튼을 구현하는 방법

JS_javascript 스킬로 버튼을 구현하는 방법

WBOY
WBOY원래의
2016-05-16 16:15:311323검색

이 글의 예시에서는 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 프로그래밍 설계에 도움이 되기를 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.