Cet article décrit comment JS implémente un bouton. Partagez-le pour votre référence. La méthode de mise en œuvre spécifique est la suivante:
<! doctype html> <html> <éadf> <meta charset = "utf-8"> <meta http-equiv = "x-ua-compatible" contenu = "edge"> <cript> window.onload = function () {var btn = new btn (); btn.init ({width: 300}); BINSEVENT (btn, 'show', function () {alert (1);}) bindEvent (btn, 'click', function () {alert (2);}) var obtn = document.getElementById ('btn'); obtn.onclick = function () {FireEvent (btn, 'show'); }} fonction btn () {this.btn = null; this.settings = {width: 200, hauteur: 40, borderradius: 6, texte: 'bouton'}; } 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 = 'solide # f00' + this.settings.borderradius + 'px'; } fonction extension (obj1, obj2) {for (var atr dans obj2) {obj1 [att] = obj2 [att]; }} Fonction BindEvent (obj, événements, fn) {obj.Listeners = obj.Listeners || {}; obj.Listeners [événements] = obj.Listers [événements] || []; Obj.Listeners [Events] .push (FN); if (obj.nodeType) {if (obj.addeventListener) {obj.addeventListener (Events, fn, false); } else {obj.attachevent ('on' + événements, fn); }}} fonction FireEvent (obj, événements) {if (obj.Listers [Events]) {for (var i dans obj.Listeners [Events]) {obj.Listeners [Events] [i] (); }}} </ script> </ head> <body> <a id = "btn" style = "margin-top: 40px;" > 12 </a> </ body> </html>J'espère que cet article sera utile à la programmation JavaScript de tous.