原型设计,便于功能点火

时间:2013-11-06 03:16:30

标签: javascript function prototype

所以我正在创建一个我将使用的JavaScript函数的小型库。有些用于UI功能,其他用于返回某些东西。下面我将发布两个代码,我想知道这个方法是否正常,并且在进一步使用这个库之前不是一个糟糕的举动,也请不要提及jQuery,因为这都是JavaScript!

HTMLElement.prototype.drag = function(bool) {   
var self = this;
self.classList.add('draggable');
    event.stopPropagation();
    event.preventDefault();
    var origLeft= parseInt(self.offsetLeft,10);
    var origTop = parseInt(self.offsetTop,10);
    var mdX = event.clientX;
    var mdY = event.clientY;
    var elements = [];
    if(bool === true){
      var j = window.localStorage.getItem('userSettings');
      if(j){
        self.style.left= j.left;
        self.style.top = j.top;
      }
    }
      function drag(bool) {
        self.style.position="absolute";
        self.style.zIndex=999;
        self.style.left = origLeft + event.clientX - mdX + "px";
        self.style.top = origTop + event.clientY - mdY + "px";
        event.stopPropagation();
      }
      function stop(bool){
        self.classList.remove('draggable');
        self.style.zIndex=0;
        document.removeEventListener('mousemove',drag,true);
        document.removeEventListener('mouseup',stop,true);
           if(bool === true){
            var settings = {
              left: self.style.left,
              top: self.style.top
            };
            var b = JSON.stringify(settings);
            window.localStorage.setItem('userSettings',b);
            console.log(b);
            }
        event.stopPropagation();
      }
       document.addEventListener('mousemove',drag,true);
       document.addEventListener('mouseup',stop,true);  
};

以上代码当然是draggable函数,下面是getClientRects()类函数但更好。

HTMLElement.prototype.getRect = function(){
     var a = this.offsetLeft;
     var b = this.offsetTop;
     var c = this.offsetHeight + b;
     var d = this.offsetWidth + a;
     var f = this.offsetHeight;
     var g = this.offsetWidth;
     var obj = { };
     obj.left = a;
     obj.right=d;
     obj.top=b;
     obj.bottom=c;
     obj.width = g;
     obj.height=f;
  return obj;
};

向您展示这一切的目的是为了获得您对原型的想法和建议,或者我不应该这样做。我喜欢像document.getElementById('div').getRect();这样的方法执行,而不是使用函数getRect('div');

0 个答案:

没有答案