JavaScript面向对象实现单选框组件详解

作者:青柠

时间:2026-10-23

浏览:531

本文详细介绍如何使用JavaScript面向对象思想实现单选框组件。通过Utile.js和UIComponent.js两个核心文件,利用原型链扩展实现组件复用,结合HTML结构展示具体应用。代码涵盖对象属性复制、事件监听及DOM操作,适合希望深入理解JS面向对象编程及UI组件封装的开发者参考。

文章目录

JS面向对象单选框实现概述

本文分享了一段基于JavaScript面向对象思想编写的单选框实现代码,供读者参考学习。

功能描述:

基于JavaScript面向对象机制的单选框功能实现。

运行效果:

JS面向对象单选框实现概述

核心代码实现细节

具体实现步骤如下:

工具类文件 Utile.js。


(function () {
 Object.prototype.addProto=function (sourceObj) {
 var names=Object.getOwnPropertyNames(sourceObj);
 for(var i=0;i<names.length;i++){
  var desc=Object.getOwnPropertyDescriptor(sourceObj,names[i]);
  if(typeof desc.value==="object" && desc.value!==null){
  var obj=new desc.value.constructor();
  obj.addProto(desc.value);//把obj当成引用对象带入递归函数继续给obj赋值
  Object.defineProperty(this,names[i],{
   enumerable:desc.enumerable,
   writable:desc.writable,
   configurable:desc.configurable,
   value:obj
  });
  continue;
  }
  Object.defineProperty(this,names[i],desc);
 }
 return this;
 };
 Function.prototype.extendClass=function (supClass) {
 function F() {}
 F.prototype=supClass.prototype;
 this.prototype=new F();
 this.prototype.constructor=this;
 this.supClass=supClass.prototype;
 if(supClass.prototype.constructor===Object.prototype.constructor){
  supClass.prototype.constructor=supClass;
 }
 }
})();
var RES=(function () {
 var list={};
 return {
 DATA_FINISH_EVENT:"data_finish_event",
 init:function (imgDataList,basePath,type) {
  if(imgDataList.length===0) return;
  if(!type) type="json";
  RES.imgDataList=imgDataList.reverse();
  RES.basePath=basePath;
  RES.type=type;
  RES.ajax(basePath+imgDataList.pop()+"."+type)
 },
 ajax:function (path) {
  var xhr=new XMLHttpRequest();
  xhr.addEventListener("load",RES.loadHandler);
  xhr.open("GET",path);
  xhr.send();
 },
 loadHandler:function (e) {
  this.removeEventListener("load",RES.loadHandler);
  var key,obj;
  if(RES.type==="json"){
  obj=JSON.parse(this.response);
  key=obj.meta.image.split(".png")[0];
  list[key]=obj.frames;
  }else if(RES.type==="xml"){
  obj=this.responseXML.children[0];
  key=obj.getAttribute("imagePath").split(".png")[0];
  list[key]=obj;
  }
 
  if(RES.imgDataList.length===0){
  var evt=new Event(RES.DATA_FINISH_EVENT);
  evt.list=list;
  document.dispatchEvent(evt);
  // Model.instance.menuData=list;
  return;
  }
  RES.ajax(RES.basePath+RES.imgDataList.pop()+"."+RES.type);
 },
 getNameJSONData:function (name) {
  var fileName=RES.basePath;
  for(var key in list){
  var arr=list[key].filter(function (t) {
   return t.filename===name;
  });
  if(arr.length>0){
   fileName+=key+".png";
   break;
  }
  }
  if(arr.length===0){
  return false;
  }else{
  return {
   file:fileName,
   w:arr[0].frame.w,
   h:arr[0].frame.h,
   x:arr[0].frame.x,
   y:arr[0].frame.y
  };
  }
 },
 getNameXMLData:function (name) {
  var fileName=RES.basePath;
  for(var key in list){
  var elem=list[key].querySelector("[n="+name+"]");
  if(elem){
   fileName+=list[key].getAttribute("imagePath");
   break;
  }
  }
  if(!elem) return false;
  return {
  file:fileName,
  w:elem.getAttribute("w"),
  h:elem.getAttribute("h"),
  x:elem.getAttribute("x"),
  y:elem.getAttribute("y")
  }
 },
 getImage:function (name) {
  var obj;
  if(RES.type==="json"){
  obj=RES.getNameJSONData(name);
  }else if(RES.type==="xml"){
  obj=RES.getNameXMLData(name)
  }
  if(!obj)return;
  var div=document.createElement("div");
  Object.assign(div.style,{
  width:obj.w+"px",
  height:obj.h+"px",
  backgroundImage:"url("+obj.file+")",
  backgroundPositionX:-obj.x+"px",
  backgroundPositionY:-obj.y+"px",
  position:"absolute"
  });
  return div;
 },
 changeImg:function (elem,name) {
  var obj;
  if(RES.type==="json"){
  obj=RES.getNameJSONData(name);
  }else if(RES.type==="xml"){
  obj=RES.getNameXMLData(name)
  }
  if(!obj)return;
  Object.assign(elem.style,{
  width:obj.w+"px",
  height:obj.h+"px",
  backgroundImage:"url("+obj.file+")",
  backgroundPositionX:-obj.x+"px",
  backgroundPositionY:-obj.y+"px",
  position:"absolute"
  });
 }
 }
})();

UI组件基类文件 UIComponent.js。


var CheckBox=(function () {
 function CheckBox(parent) {
 this.checkView=this.init(parent);
 }
 /*
 //ES5 单例
 CheckBox.getInstance=function () {
 if(!CheckBox._instance){
  CheckBox._instance=new CheckBox();
 }
 return CheckBox._instance;
 };*/
 CheckBox.prototype.addProto({
 _label:"",
 _checked:false,
 init:function (parent) {
  if(this.checkView) return this.checkView;
  var div=document.createElement("div");
  var icon=RES.getImage("f-checkbox");
  div.appendChild(icon);
  var label=document.createElement("span");
  div.style.position=icon.style.position=label.style.position="relative";
  icon.style.float=label.style.float="left";
  label.textContent="";
  Object.assign(label.style,{
  fontSize:"16px",
  lineHeight:"20px",
  marginLeft:"5px",
  marginRight:"10px"
  });
  var h=RES.getNameXMLData("f-checkbox").h;
  icon.style.top=(20-h)/2+"px";
  div.appendChild(label);
  parent.appendChild(div);
  this.clickHandlerBind=this.clickHandler.bind(this);
  div.addEventListener("click",this.clickHandlerBind);
  return div;
 },
 clickHandler:function (e) {
  this.checked=!this.checked;
 },
 set label(value){
  this._label=value;
  this.checkView.lastElementChild.textContent=value;
 },
 get label(){
  return this._label;
 },
 set checked(value){
  if(this._checked===value)return;
  this._checked=value;
  if(value){
  RES.changeImg(this.checkView.firstElementChild,"f-checkbox-active");
  }else{
  RES.changeImg(this.checkView.firstElementChild,"f-checkbox");
  }
  this.checkView.firstElementChild.style.position="relative";
  this.dispatchMessage(value);
 },
 dispatchMessage:function (value) {
  var evt=new Event("change");
  evt.checked=value;
  evt.elem=this;
  document.dispatchEvent(evt);
 },
 get checked(){
  return this._checked;
 }
 });
 return CheckBox;
})();
 
var Radio=(function () {
 function Radio(parent,groupName) {
 this.constructor.supClass.constructor.call(this,parent);
 this.groupName=groupName;
 this.checkView.self=this;
 this.checkView.setAttribute("groupName",groupName);
 }
 
 Radio.extendClass(CheckBox);
 
 Radio.prototype.addProto({
 clickHandler:function (e) {
  // console.log(Model.instance.menuData);
  if(this.checked)return;
  var list=document.querySelectorAll("[groupName="+this.groupName+"]");
  for(var i=0;i<list.length;i++){
  list[i].self.checked=false;
  }
  this.checked=true;
 },
 dispatchMessage:function (value) {
  if(!value)return;
  this.constructor.supClass.dispatchMessage.call(this,value);
 }
 });
 return Radio;
})();

HTML页面集成示例

HTML结构示例。


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <script src="js/Model.js"></script>
 <script src="js/Utile.js"></script>
 <script src="js/UIComponent.js"></script>
 
</head>
<body>
 <script>
 document.addEventListener(RES.DATA_FINISH_EVENT,init);
 RES.init(["new_icon"],"img/","xml");
 var arr=["北京","上海","广州","深圳","成都"];
 
 function init() {
  document.addEventListener("change",changeHandler);
  var elem=document.createDocumentFragment();
  for(var i=0;i<arr.length;i++){
  var radio=new Radio(elem);
  radio.label=arr[i];
  if(i===0){
   radio.checked=true;
  }
  }
  document.body.appendChild(elem);
 
 }
 
 function changeHandler(e) {
  console.log(e);
 }
 
 
 
 Model.instance.elem.addEventListener("chi",chiHandler);
 
 Model.instance.elem.dispatchEvent(new Event("chi"));
 
 function chiHandler(e) {
  console.log(e)
 }
 </script>
</body>
</html>

以上内容为本文的全部介绍,希望对读者的学习有所助益,欢迎继续支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章