JS實(shí)用技巧手記(五)

2018-06-17 19:26 更新

本系列文章旨在記錄一些實(shí)用的javascript技巧,既可以作為一個(gè)知識(shí)的積累,又可以作為閑暇時(shí)打發(fā)時(shí)間寫(xiě)寫(xiě)代碼的記錄。同時(shí)也方便日后翻閱~

1. 十六進(jìn)制顏色值的隨機(jī)生成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function randomColor(){
var arrHex=["0","1","2","3","4","5","6","7","8","9","a","b","c","d"],
     strHex="#",
     index;
     for(var i=0;i<6;i++){
      index=Math.floor(Math.random()*14);
      strHex+=arrHex[index];
     }
return strHex;
}
console.log(randomColor());
function getRandomColor(){
    return "#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6);
}
console.log(getRandomColor());

說(shuō)明:

1、16777215為16進(jìn)制的顏色ffffff轉(zhuǎn)成10進(jìn)制的數(shù)字

2、>>數(shù)字取整

3、轉(zhuǎn)成16進(jìn)制不足6位的以0來(lái)補(bǔ)充

 

2. 獲取下一個(gè)結(jié)點(diǎn),兼容IE和Firefox

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function getNextNode(node){
      node = typeof node == "string" ? document.getElementById(node) : node;
      var nextNode = node.nextSibling;
      if(!nextNode) return null;
    if(!document.all){    
        while(true){
            if(nextNode.nodeType == 1){
                break;
            } else {
                if(nextNode.nextSibling){
                    nextNode = nextNode.nextSibling;
                } else {
                    break;
                }
            }
          }
    }  
    return nextNode;  
};
// demo:
var nextNode = getNextNode("item");   //傳遞當(dāng)前元素id
console.log(nextNode.id);              //返回nextSibling的id

3. 設(shè)置透明度

1
2
3
4
5
6
7
8
9
10
11
function setOpacity(node, level){
    node = typeof node == "string" ? document.getElementById(node) : node;
    if (document.all){
        node.style.filter = 'alpha(opacity=' + level + ')';
    } else {
        node.style.opacity = level / 100;
    }
}
// demo:
setOpacity("test1",20);
setOpacity("test2",80);

4. Event兼容

1
2
3
4
5
6
7
8
9
10
11
12
13
// 兼容IE和firefox的event對(duì)象
btn.onclick = function(e){
    e = window.event || e;
    //下面可以用e來(lái)做點(diǎn)什么事,e在IE和Firefox下都指向了event對(duì)象
}
// 兼容srcElement和target
var el = e.srcElement || e.target;
console.log(el.tagName);
// 封裝getEventTarget函數(shù)
function getEventTarget(e){
    e = window.event || e;
    return e.srcElement || e.target;
}

5. 阻止冒泡,封裝stopPropagation函數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
function stopPropagation(e){
    e = window.event || e;
    if(document.all){
        e.cancelBubble=true;  
    } else {
          e.stopPropagation();
    }
}
// demo:
btn.onclick = function(e){
    stopPropagation(e);
}

6. 事件監(jiān)聽(tīng)兼容函數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function on(node,eventType,handler){
    node = typeof node == "string" ? document.getElementById(node) : node;
    if(document.all){
        node.attachEvent("on"+eventType,handler);  
    } else {
        node.addEventListener(eventType,handler,false);  
    }
}
// demo:
var btn = document.getElementById("btn");
on(btn,"click",function(){
    console.log(1);
});
// 增強(qiáng)函數(shù)
// IE下this指向window,其他瀏覽器指向當(dāng)前元素
on = function(node,eventType,handler,scope){
  node = typeof node == "string" ? document.getElementById(node) : node;
  scope = scope || node;
  if(document.all){
    node.attachEvent("on"+eventType,function(){handler.apply(scope,arguments)});
  } else {  
    node.addEventListener(eventType,function(){handler.apply(scope,arguments)},false);
  }
}

7. 類型判斷函數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function isNumber(s){
    return !isNaN(s);
}
function isString(s){
    return typeof s == "string";
}
function isBoolean(s){
    return typeof s == "boolean";
}
function isFunction(s){
    return typeof s == "function";
}
function isNull(s){
    return s == null;
}
function isUndefined(s){
    return typeof s == "undefined";
}
function isEmpty(s){
    return /^\s*$/.test(s);
}
function isArray(s){
    return s instanceof Array;
}

8. getByClass、getById、getByTag

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
var get={
  byId:function(id){
    return document.getElementById(id);
  },
  byClass:function(oParent,sClass){
    if(oParent.getElementsByClass){
      retuen (oParent||document).getElementsByClass(sClass);
    }else{
      var aClass=[];
      var reClass=new  RegExp("(^|)"+sClass+"( |$)");
      var aElem=this.byTag(oParent,"*");
      for(var i=0;i<aElem.length;i++){
        // reClass.test(aElem[i].className) && aClass.push(aElem[i]);
        if(reClass.test(aElem[i].className)){
          aClass.push(aElem[i]);
        }
      }
      return aClass;
    }
  },
  byTag:function(obj,elem){
    return (obj||document).getElementsByTagName(elem);
  }
}
// demo:
var oNav = get.byId("nav");
var aLi = get.byTagName("li", oNav);
var aSubNav = get.byClass("subnav", oNav);

9. getByClass

1
2
3
4
5
6
7
8
9
10
11
12
13
function getByClass(oParent, sClassName)
{
    var aElm=oParent.getElementsByTagName('*');
    var aArr=[];
    for(var i=0; i<aElm.length; i++)
    {
        if(aElm[i].className==sClassName)
        {
            aArr.push(aElm[i]);
        }
    }
    return aArr;
}

10. extend函數(shù)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function extend(subClass,superClass){
var F = function(){};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;
  subClass.superclass = superClass.prototype;
  if(superClass.prototype.constructor == Object.prototype.constructor){
    superClass.prototype.constructor = superClass;
  }
}
function Animal(name){
this.name = name;
this.type = "animal"
}
Animal.prototype = {
say : function(){
  alert("I'm a(an) " + this.type + " , my name is " + this.name);
}
}
function Bird(name){
  this.constructor.superclass.constructor.apply(this,arguments);
  this.type = "bird"
}
extend(Bird,Animal);
  Bird.prototype.fly = function(){
  alert("I'm flying");
}
var canary = new Bird("xiaocui");
canary.say();   // I’m a(an) bird , my name is xiaocui
canary.fly(); // I’m flying

 

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)