外部リンクを拾って、クラス名をつけたり新しいウインドウで開くようにしたりするJavaScriptです。
こんな風に使います。
1 2 | var ob = new OutboundLink(); ob.limitByClassName("entryBody"); |
他に以下のような設定ができます。
limitById(id:String)
走査対象を特定のid
が指定された要素に限定します。
limitByClassName(name:String)
走査対象を特定のclass
が指定された要素に限定します。
useNewClassName(b:Boolean)
クラス名をつけるかどうか設定します。初期値はtrue
です。
additionalClassName(name:String)
追加するクラス名を指定します。初期値は"outbound"
です。CSSで.outbound
というクラスを指定しておけば、そのスタイルを反映できます。
useFilterIMG(b:Boolean)
a
要素の子要素にimg
要素がある場合、そのa
要素を走査対象から除外します。初期値はtrue
です。
useNewWindow(b:Boolean)
新しいウィンドウで開くように設定します。新しいウィンドウはtarget
属性を使用しないValidなコードです。初期値はtrue
です。
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | // // outboundlink.js // OutboundLink = function() { this.els = []; this.use_new_class = true; this.additional_classname = "outbound"; this.use_filter_IMG = true; this.use_new_window = true; // this.onLoad(this,"init"); } OutboundLink.prototype.limitById = function(id) { this._id = id; } OutboundLink.prototype.limitByClassName = function(name) { this._classname = name; } OutboundLink.prototype.useNewClassName - function(b) { this.use_new_class = b; } OutboundLink.prototype.additionalClassName = function(name) { this.additional_classname = name; } OutboundLink.prototype.useFilterIMG = function(b) { this.use_filter_IMG = b; } OutboundLink.prototype.useNewWindow = function(b) { this.use_new_window = b; } OutboundLink.prototype.onLoad = function(scope, func) { if(window.addEventListener) window.addEventListener("load", function(e){ scope[func](e); }, false ); else if(window.attachEvent) window.attachEvent("onload", function(e){ scope[func](e); }); } OutboundLink.prototype.init = function() { if(this._classname) this.els = this.getElementsByClassName(this._classname); else if(this._id) this.els.push(document.getElementById(this._id)); else this.els.push(document.body); // var e = this.els; for(i=0,len=e.length; i<len; i++) { var a = e[i].getElementsByTagName("a"); if(this.use_filter_IMG) a = this.filterIMG(a); // for(j=0,len2=a.length; j<len2; j++) { var el = a[j], href = el.href; if(!!(href.match(/^https?:.+/))) { if(this.use_new_class) el.setAttribute("class",this.additional_classname); if(this.use_new_window) el.setAttribute("onclick","window.open(this.href); return false;"); } } } } OutboundLink.prototype.filterIMG = function(nodelist) { var e=[]; for(var i=0,len=nodelist.length; i<len; i++) { var n = nodelist[i], tn = ""+n.firstChild.tagName; if(!(tn.match(/img/i))) e.push(n); } return e; } OutboundLink.prototype.getElementsByClassName = function(_classname) { var e = []; var a = document.getElementsByTagName("*"); for(var i=0,len=a.length; i<len; i++) { var n = a[i].className; if(n&&n==_classname) e.push(a[i]); } return e; } |