1. 程式人生 > >插件的鏈式調用(利用當前對象)

插件的鏈式調用(利用當前對象)

key .text else var splitter attribute rip option lis

(function () {
	var options = {
		splitter: ‘char‘
	}
	//獲取隨機顏色
	var getRandomColor = function(){
	  return ‘hsla(‘ + (Math.random() * 360) + ‘, 100%, 50%, 1)‘;
	}
    //主要功能函數
	function injector(t, splitter) {
		var text = t.textContent,
			//a = text.split(splitter),
			a,
			after,
            newText = ‘‘;
		if(splitter === ‘char‘) {
			a = text.split(‘‘);
			after = ‘‘;
		}
		else if (splitter === ‘word‘) {
			a = text.split(‘ ‘);
			after = ‘ ‘;
		}
		else if (splitter === ‘line‘) {
			var r = t.innerHTML;
			var e = document.createElement(‘div‘);
			r = r.replace(/<br>/ig, ‘eefec303079ad17405c889e092e105b0‘);
			e.innerHTML = r;
			text = e.textContent;
			a = text.split(‘eefec303079ad17405c889e092e105b0‘);
			after = ‘‘;
			e = null;//free storge
		}


		if (a.length) {
			for(var i = 0; i < a.length; i++) {
				var font_color = getRandomColor();
                newText += ‘<span style="color:‘+font_color+‘">‘ + a[i] + ‘</span>‘ + after;
			}
			//t.setAttribute(‘aria-label‘, text);
			t.innerHTML = newText;
		}
	}
	//API插件函數
	var api = {
		//配置函數
		config: function (opts) {
			if(!opts) return options;
			for(var key in opts) {
				options[key] = opts[key];
			}
			return this;
		},
        //監聽函數
		listen: function listen(elem) {
			if (typeof elem === ‘string‘) {
				var elems = document.querySelectorAll(elem),
					i = elems.length;
					while (i--) {
						listen(elems[i]);
					}
					return
			}
			//調用功能
			injector(elem, options.splitter);

			return this;
		}
	}
	//暴露給全局
	this.ColorDivide = api;
})();

  

<script src="ColorDivide.js"></script>
	<script>
	ColorDivide.listen(‘#demo1‘);                                       //插件的鏈式調用(利用當前對象)
	ColorDivide.config({splitter: ‘word‘}).listen(‘#demo2‘);            //插件的鏈式調用(利用當前對象)
	ColorDivide.config({splitter: ‘line‘}).listen(‘#demo3‘);            //插件的鏈式調用(利用當前對象)
	</script>

  

插件的鏈式調用(利用原型鏈)下回析解。。。。。。。。。。。。。。。。。。

插件的鏈式調用(利用當前對象)