--------------------华丽分割线-----------------------------
/**
获取元素到页面顶端的距离(出自jquery源码)
*/
function getCoords(el) {
if (typeof el == 'string') {
el = Fid(el);
}
var box = el.getBoundingClientRect(),
doc = el.ownerDocument,
body = doc.body,
html = doc.documentElement,
clientTop = html.clientTop || body.clientTop || 0,
clientLeft = html.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || html.scrollTop || body.scrollTop) - clientTop,
left = box.left + (self.pageXOffset || html.scrollLeft || body.scrollLeft) - clientLeft
return {
'top' : top,
'left' : left
};
};
/*
获取元素到页面顶端的
document.documentElement.clientLeft ie6/7 下2px的bodrer
*/
function getAbsPoint(e) {
if (typeof e == 'string') {
e = Fid(e);
}
var x = e.offsetLeft;
var y = e.offsetTop;
var de = document.documentElement;
while (e = e.offsetParent) { //在IE下offset对象是对当前元素到上一级元素的距离,FF则是正常的
x += e.offsetLeft;
y += e.offsetTop;
//需要加上元素自身的border, offsetTop 本身就包含margin
if (e && e != de && !Browser.isOpera) {
x += e.clientLeft;
y += e.clientTop; //ie6下设置元素宽度后才能到获取他的边框大小,如果不设置则下级取上级的时候会把上级的边框算进去(总体计算还是没有错)
}
}
return {
"left" : x,
"top" : y
};
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//浏览器类型检测
var FBrowser=(function(){
var ua = navigator.userAgent;
var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
return {
isIE: !!window.attachEvent && window.ActiveXObject && !isOpera,
isOpera: isOpera,
isSafari: ua.indexOf('AppleWebKit/') > -1,
isFirefox: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1,
MobileSafari: /Apple.*Mobile.*Safari/.test(ua),
isChrome: !!window.chrome,
};
})();
FBrowser.isIE6=FBrowser.isIE&&!window.XMLHttpRequest;
FBrowser.isIE7=FBrowser.isIE&&!!window.XMLHttpRequest;
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//document.documentMode ie8+以上显示浏览器版本
var IE = (function(){
var ie = !!window.ActiveXObject;
e = {
isIE: !!window.ActiveXObject,
isIE6: ie && !window.XMLHttpRequest,
isIE7: ie && window.XMLHttpRequest && document.documentMode == 7,
isIE8: ie && window.XMLHttpRequest && document.documentMode == 8,
isIE9: ie && window.XMLHttpRequest && document.documentMode == 9
}
return e;
})();
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
获取元素样式
处理透明度、元素浮动样式的获取 ,结果带有单位
*/
function getStyle(elem, name) {
var nameValue = null;
if (document.defaultView) {
var style = document.defaultView.getComputedStyle(elem, null);
nameValue = name in style ? style[name] : style.getPropertyValue(name);
} else {
var style = elem.style,
curStyle = elem.currentStyle;
//透明度 from youa
if (name == "opacity") {
if (/alpha\(opacity=(.*)\)/i.test(curStyle.filter)) {
var opacity = parseFloat(RegExp.$1);
return opacity ? opacity / 100 : 0;
}
return 1;
}
if (name == "float") {
name = "styleFloat";
}
var ret = curStyle[name] || curStyle[camelize(name)];
//单位转换 from jqury
if (!/^-?\d+(?:px)?$/i.test(ret) && /^\-?\d/.test(ret)) {
var left = style.left,
rtStyle = elem.runtimeStyle,
rsLeft = rtStyle.left;
rtStyle.left = curStyle.left;
style.left = ret || 0;
ret = style.pixelLeft + "px";
style.left = left;
rtStyle.left = rsLeft;
}
nameValue = ret;
}
return nameValue === 'auto' ? '0px' : nameValue;
}
//将CSS属性名由驼峰式转为普通式
function uncamelize(s) {
return s.replace(/[A-Z]/g,function (c) {
return '-'+c.charAt(0).toLowerCase();
});
}
//将CSS属性名转换成驼峰式
function camelize(s) {
return s.replace(/-[a-z]/gi,function (c) {
return c.charAt(1).toUpperCase();
});
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//each
function each( object, callback ) {
if ( undefined === object.length ){
for ( var name in object ) {
if (false === callback( object[name], name, object )) break;
}
} else {
for ( var i = 0, len = object.length; i < len; i++ ) {
if (i in object) { if (false === callback( object[i], i, object )) break; }
}
}
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//获取scrolltop
function getScrollTop()
{
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
return scrollTop;
}
//设置scrolltop
function setScrollTop(top)
{
document.documentElement.scrollTop = document.body.scrollTop = top;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
获取浏览器可视区域的尺寸
*/
function getBrowserSize()
{
//在标准模式下用 documentElement, 在怪癖模式下用 body
return {
width:document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth,
height:document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight,
}
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
获取页面大小
*/
function getPageSize()
{
//ie下优先取 body
return {
width:document.body.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth,
height: document.body.scrollHeight ? document.body.scrollHeight : document.documentElement.scrollHeight
}
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
* 根据类名获取元素
*
* @param className
* @param context
* @returns
*/
function getByClassName(className,context) {
context=context || document;
if (context.getElementsByClassName) {
return context.getElementsByClassName(className);
}
var nodes=context.getElementsByTagName('*'),ret=[];
for (var i=0;i<nodes.length;i++) {
if (nodes[i].nodeType == 1 && nodes[i].className.indexOf(className) != -1)
{
ret.push(nodes[i]);
}
}
return ret;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
* Registers a callback for DOM ready.
If DOM is already ready, the
* callback is called immediately.
* @param {Function} Array callback
*/
function domReady(callback) {
var isTop, testDiv, scrollIntervalId,
isPageLoaded = false,
doc = document,
readyCalls = [];
function runCallbacks(callbacks) {
var i;
for (i = 0; i < callbacks.length; i += 1) {
callbacks[i](doc);
}
}
function callReady() {
var callbacks = readyCalls;
if (isPageLoaded) {
//Call the DOM ready callbacks
if (callbacks.length) {
readyCalls = [];
runCallbacks(callbacks);
}
}
}
/**
* Sets the page as loaded.
*/
function pageLoaded() {
if (!isPageLoaded) {
isPageLoaded = true;
if (scrollIntervalId) {
clearInterval(scrollIntervalId);
}
callReady();
}
}
if (document.addEventListener) {
//Standards. Hooray! Assumption here that if standards based,
//it knows about DOMContentLoaded.
document.addEventListener("DOMContentLoaded", pageLoaded, false);
window.addEventListener("load", pageLoaded, false);
} else if (window.attachEvent) {
window.attachEvent("onload", pageLoaded);
testDiv = document.createElement('div');
try {
isTop = window.frameElement === null;
} catch (e) {}
//DOMContentLoaded approximation that uses a doScroll, as found by
//Diego Perini: http://javascript.nwbox.com/IEContentLoaded/,
//but modified by other contributors, including jdalton
if (testDiv.doScroll && isTop && window.external) {
scrollIntervalId = setInterval(function () {
try {
testDiv.doScroll();
pageLoaded();
} catch (e) {}
}, 1);
}
}
//Check if document already complete, and if so, just trigger page load
//listeners. Latest webkit browsers also use "interactive", and
//will fire the onDOMContentLoaded before "interactive" but not after
//entering "interactive" or "complete". More details:
//http://dev.w3.org/html5/spec/the-end.html#the-end
//http://stackoverflow.com/questions/3665561/document-readystate-of-interactive-vs-ondomcontentloaded
//Hmm, this is more complicated on further use, see "firing too early"
//bug: https://github.com/requirejs/domReady/issues/1
//so removing the || document.readyState === "interactive" test.
//There is still a window.onload binding that should get fired if
//DOMContentLoaded is missed.
if (document.readyState === "complete") {
pageLoaded();
}
if (isPageLoaded) {//dom已经ready
callback(doc);
} else {
readyCalls.push(callback);
}
}
domReady(function(){
alert('domload');
alert(document.getElementById('container'));
})
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//改变某个函数的内部this指针
function closure(fn, scope)
{
return function (){
fn.apply(scope, arguments);
};
}
//调用某个对象的某个函数,并将次对象作为方法的作用域
function invoke(obj, methodName)
{
return function(){
obj.methodName.apply(obj, arguments);
};
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
// 元素数据缓存
(function(){
var cache = [0],
expando = 'data' + +new Date();
function data(elem) {
var cacheIndex = elem[expando],
nextCacheIndex = cache.length;
if(!cacheIndex) {
cacheIndex = elem[expando] = nextCacheIndex;
cache[cacheIndex] = {};
}
return {
get : function(key) {
if(typeof key === 'string')
{
return cache[cacheIndex] ? cache[cacheIndex][key] : null;
}
return cache[cacheIndex] ? cache[cacheIndex] : null;
},
set : function(key, val) {
cache[cacheIndex][key] = val;
return data(elem);
},
remove : function(key){
if(cache[cacheIndex])
{
return cache.splice(cacheIndex,1);
}
}
}
}
window.data = data;
})();
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//js请求xml文件,
if (window.ActiveXObject) {
//IE
var getXMLDOM=function () {
return new ActiveXObject("Microsoft.XmlDom");
},loadXMLFile=function (xmlDom,url,callback) {
xmlDom.onreadystatechange=function () {
if (xmlDom.readyState===4) {
if (xmlDom.parseError.errorCode===0) {
callback.call(xmlDom);
} else {
throw new Error("XML Parse Error:"+xmlDom.parseError.reason);
}
}
};
xmlDom.load(url);
return xmlDom;
},loadXMLString=function (xmlDom,s) {
xmlDom.loadXML(s);
if (xmlDom.parseError.errorCode!==0) {
throw new Error("XML Parse Error:"+xmlDom.parseError.reason);
}
return xmlDom;
},
getXML=function (xmlNode) {
return xmlNode.xml;
};
}else if (document.implementation && document.implementation.createDocument) {
//W3C
var getXMLDOM=function () {//获取一个XMLDOM对象
return document.implementation.createDocument("","",null);
},
loadXMLFile=function (xmlDom,url,callback) {
if (xmlDom.async===true) {
xmlDom.onload=function () {
if (xmlDom.documentElement.nodeName=="parsererror") {
throw new Error("XML Parse Error:"+xmlDom.documentElement.firstChild.nodeValue);
} else {
callback.call(xmlDom);
}
};
}
console.dir(xmlDom);
xmlDom.load(url);
return xmlDom;
},
loadXMLString=function (xmlDom,s) {
var p = new DOMParser();
var newDom=p.parseFromString(s,"text/xml");
if (newDom.documentElement.nodeName=="parsererror") {
throw new Error("XML Parse Error:"+newDom.documentElement.firstChild.nodeValue);
}
while (xmlDom.firstChild) {
xmlDom.removeChild(xmlDom.firstChild);
}
for (var i=0,n;i<newDom.childNodes.length;i++) {
n=xmlDom.importNode(newDom.childNodes[i],true);
//importNode用于把其它文档中的节点导入到当前文档中
//true参数同时导入子节点
xmlDom.appendChild(n);
}
return xmlDom;
},
getXML=function (xmlNode) {
var s= new XMLSerializer();
return s.serializeToString(xmlNode,"text/xml");
};
}
var xmldom = getXMLDOM();
loadXMLFile(xmldom,"/xml.php",function () {
alert(this);
});
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
ajax
args {
url
method 默认值为get
success Function
data {key:value}
cache Boolean true表示缓存,默认值为false
datatype 默认 text text|xml
}
*/
function ajax(args) {
//创建xhr对象
function createXHR() {
return window.XMLHttpRequest?
new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");//IE6
}
//拼接参数
function params(o) {
var a=[];
for (var i in o) {
a.push(encodeURIComponent(i)+"="+encodeURIComponent(o[i]));
}
return a.join("&");
}
var xhr = createXHR();
args.method=args.method || "get";
if (!args.cache) {
args.data.cache = (new Date()*1);
}
var data_str = params(args.data)
if (/get/i.test(args.method) && data_str) {
args.url += args.url.indexOf("?")<0 ? '?' : '&';
args.url += data_str;
}
xhr.open(args.method,args.url,true);
xhr.onreadystatechange=function () {
if (xhr.readyState===4 && xhr.status===200) {
if(!args.datatype || args.datatype.toLowerCase() === 'text')
{
args.success(xhr.responseText);
}else{
args.success(xhr.responseXML);
}
}
};
if (/post/i.test(args.method)) {
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(data);
} else {
xhr.send();
}
}
ajax({
url:"/xml.php",
method:'post',
success:function(xmldom){
alert(xmldom.nodeName);
},
data:{id:1},
datatype:'xml'
})
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//获取firstchild
function firstChild(elem)
{
var node = elem.firstChild ? elem.firstChild : null;
while(node && node.nodeType != 1)
{
node = node.nextSibling;
}
return node;
}
//获取下一个同辈元素(ie下回忽略空白文节点)
function next(elem)
{
var node = elem.nextSibling ? elem.nextSibling : null;
while(node && node.nodeType != 1 )
{
node = node.nextSibling;
}
return node;
}
//获取上一个同辈元素(ie下回忽略空白文节点)
function prev(elem)
{
var node = elem.previousSibling ? elem.previousSibling : null;
while(node && node.nodeType != 1 )
{
node = node.previousSibling;
}
return node;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
* 获取指定类名的父元素
* @param elem
* @param className
* @returns
*/
function parents(elem, className)
{
//检测自身是否满足条件
if(elem.className.indexOf(className) != -1)
{
return elem;
}
var parent = null;
while((parent = elem.parentNode) && parent.nodeType == 1 && !!className)
{
if(parent.className.indexOf(className) != -1)
{
break;
}
elem = parent;
}
return parent;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//输入html代码,输出转换后的代码
function htmlEncode( html )
{
//使用div来模拟
var div = document.createElement("div");
if(typeof div.innerText != 'undefined')
{
div.innerText = html;
}else{
div.textContent = html;
}
var html_encode = div.innerHTML;
div = null;
return html_encode;
}
function htmlDecode( html )
{
//使用div来模拟
var text, div = document.createElement("div");
div.innerHTML = html;
if(typeof div.innerText != 'undefined')
{
text = div.innerText;
}else{
text = div.textContent;
}
return text;
}
function htmlEncode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/\&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\'/g, "'");
s = s.replace(/\"/g, """);
return s;
}
function htmlDecode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/'/g, "\'");
s = s.replace(/"/g, "\"");
return s;
}
function htmlEncode(html)
{
var div = document.createElement("div");
var text = document.createTextNode("");
div.appendChild(text);
text.nodeValue=html;
return div.innerHTML;
}
function htmlDecode(str)
{
var div = document.createElement("div");
div.innerHTML = str;
return div.firstChild.nodeValue;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//计算数组中的最大值
Array.prototype.max = function(){
return Math.max.apply({},this)
}
//计算数组中的最小值
Array.prototype.min = function(){
return Math.min.apply({},this)
}
//复制数组
Array.prototype.copy =
function() {
return [].concat(this);
};
//去除数组中只指定元素,只能去除一个,如果想多个,之前先用unique处理
Array.prototype.remove = function(value){
for(var i=0,len=this.length;i<len;i++)
{
if(this[i]==value){
this.splice(i, 1);
break;
}
}
return this;
}
//去除数组中只指定元素,只能去除一个,如果想多个,之前先用unique处理
Array.prototype.inArray = function(value){
var index = -1;
each(this,function(v,k){
if(v == value){
index = k;
return false;
}
})
return index;
}
//去除数组中的重复元素
Array.prototype.unique = function(){
var rst = [];
each(this, function(v,k){
if(rst.inArray(v)<0) rst.push(v);
})
return rst;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
String.prototype.repeat
String.prototype.repeat=function(n){return new Array(n+1).join(this);}
String.prototype.ltrim
String.prototype.ltrim=function(){return this.replace(/^\s*/, "");}
String.prototype.rtrim
String.prototype.rtrim=function(){return this.replace(/\s*$/, "");}
String.prototype.trim
String.prototype.trim=function(){return this.rtrim().ltrim();}
//非ascii字符
String.prototype.hasChinese=function(){return /[^\u00-\uff]/g.test(this);}
//包括中英韩文,这三种语言里面有更多共同的
String.prototype.onlyChinese=function(){return /^[\u0391-\u9FBF]+$/g.test(this);}
//取得字符串实际长度(汉字算两个字节,英文字母算一个字节) \x代表ascii码,会按unicode码进行匹配
String.prototype.bytes=function(){ return this.replace(/[^\x00-\xff]/gi,'xx').length;}
Number.prototype.inter
Number.prototype.inter=function (a,b) {//检测数字是否在区间之内
var min=Math.min(a,b),max=Math.max(a,b);
return this==a || this==b || (Math.max(this,min)==this && Math.min(this,max)==this);
};
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//过滤空白文本节点
function filterSpaceNode(nodes) {掉
var ret=[];
for(var i=0;i<nodes.length;i++) {
if (nodes[i].nodeType===3
&& /^\s+$/.test(nodes[i].nodeValue)) {
continue;
}
ret.push(nodes[i]);
}
return ret;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
addClassName
function addClassName(obj,cn) {
return obj.className += " " + cn;
}
delClassName
function delClassName(obj,cn) {
return obj.className = obj.className.replace(new RegExp("\\b"+cn+"\\b"),"");
//同样,多个className之间的多个空格也会被视为一个
}
hasClassName
function hasClassName(obj,cn) {
return (new RegExp("\\b"+cn+"\\b")).test(obj.className);
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
placeNode
function placeNode(node,fn,__this) {
fn.call(__this,frag(node));
return __this;
}
append
function append(node, newNode) {
return placeNode(newNode,function (one) {node.appendChild(one)},node);
}
preappend
function preappend(node, newNode) {
return placeNode(newNode,function (one) {node.insertBefore(one,node.firstChild)},node);
}
before
function before(node, newNode) {
return placeNode(newNode,function (one) {node.parentNode.insertBefore(one,node)},node);
}
after
function after(node, newNode) {
//如果node有下一个节点的话,newNode 插入到node.nextSibling的前面
//如果node没有下一个节点,newNode插入为node.parentNode的最后一个子
if (node.nextSibling) {
placeNode(newNode,function (one) {node.parentNode.insertBefore(one,node.nextSibling)},node);
} else {
placeNode(newNode,function (one) {node.parentNode.appendChild(one)},node);
}
return node;
}
replaceNode
//如果新节点是页面中已经存在的则新节点原来的位置会消失
function replaceNode(newNode, node) {
node.parentNode.replaceChild(newNode, node);
}
delNode
function delNode(node) {
node.parentNode.removeChild(this);
}
frag
function frag(nodes) {
var tempFrag =document.createDocumentFragment();
if (nodes.nodeType) {nodes=[nodes];}
/* 错误的写法 传入的是引用
each(nodes,function(node){
tempFrag.appendChild(node);
})*/
for(var i=0;i<nodes.length;i++) {
//克隆后不在是引用
var a = nodes[i].cloneNode(true);
(function(node){
tempFrag.appendChild(node);
})(a)
}
/*
while(nodes.length>0)
{
tempFrag.appendChild(nodes[0]);
alert(nodes.length);
}
*/
return tempFrag;
}
//html转换为对象
function html2Obj(html)
{
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//数据的本地化存储,都兼容
function makeWebStorage() {
//ie用userdata实现,w3c浏览器本身支持
if (!("localStorage" in window)) {
var store = {
userData : null,
name : location.hostname,
init : function () {
if (!store.userData) {
try {
store.userData = document.createElement('INPUT');
store.userData.type = "hidden";
store.userData.style.display = "none";
store.userData.addBehavior("#default#userData");
document.body.appendChild(store.userData);
var expires = new Date();
expires.setDate(expires.getDate() + 365);
store.userData.expires = expires.toUTCString();
} catch (e) {
return false;
}
}
return true;
},
setItem : function (key, value) {
if (store.init()) {
store.userData.load(store.name);
store.userData.setAttribute(key, value);
store.userData.save(store.name);
}
},
getItem : function (key) {
if (store.init()) {
store.userData.load(store.name);
return store.userData.getAttribute(key)
}
},
remove : function (key) {
if (store.init()) {
store.userData.load(store.name);
store.userData.removeAttribute(key);
store.userData.save(store.name);
}
}
};
}else{
store = {
set:function(key, value){localStorage.setItem(key, value)},
get:function(key){return localStorage.getItem(key)},
remove:function(key){return localStorage.removeItem(key)}
}
}
window.webStorage = store;
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
* 记录函数调用的次数
*/
function invokeTimes(){
if(arguments.callee.times == undefined)
{
arguments.callee.times = 0;
}
arguments.callee.times ++;
console.log(arguments.callee.times);
}
document.body.onclick = function(){
invokeTimes();
}
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
/**
*javascript按字节进行截取
*
* param str 要截取的字符串
* param L 要截取的字节长度,注意是字节不是字符,一个汉字两个字节
* return 截取后的字符串
*/
function cutStr(str,L){
var result = '',
strlen = str.length, // 字符串长度
chrlen = str.replace(/[^\x00-\xff]/g,'**').length; // 字节长度
if(chrlen<=L){return str;}
for(var i=0,j=0;i<strlen;i++){
var chr = str.charAt(i);
if(/[\x00-\xff]/.test(chr)){
j++; // ascii码为0-255,一个字符就是一个字节的长度
}else{
j+=2; // ascii码为0-255以外,一个字符就是两个字节的长度
}
if(j<=L /* || j==L+1 */){ // 当加上当前字符以后,如果总字节长度小于等于L,则将当前字符真实的+在result后
result += chr;
}else{ // 反之则说明result已经是不拆分字符的情况下最接近L的值了,直接返回
return result;
}
}
}
// 用例
alert(cutStr("abc中英文混合",10));
--------------------华丽分割线-----------------------------
--------------------华丽分割线-----------------------------
//变量定义 效果同php中的define函数
function define (name, value) {
// Define a new constant
//
// version: 903.3016
// discuss at: http://phpjs.org/functions/define
// + original by: Paulo Freitas
// + revised by: Andrea Giammarchi (http://webreflection.blogspot.com)
// + reimplemented by: Brett Zamir (http://brett-zamir.me)
// * example 1: define('IMAGINARY_CONSTANT1', 'imaginary_value1');
// * results 1: IMAGINARY_CONSTANT1 === 'imaginary_value1'
var defn, replace, script, that = this,
d = this.window.document;
var toString = function (name, value) {
return 'const ' + name + '=' + (/^(null|true|false|(\+|\-)?\d+(\.\d+)?)$/.test(value = String(value)) ? value : '"' + replace(value) + '"');
};
try {
eval('const e=1');
replace = function (value) {
var replace = {
"\x08": "b",
"\x0A": "\\n",
"\x0B": "v",
"\x0C": "f",
"\x0D": "\\r",
'"': '"',
"\\": "\\"
};
return value.replace(/\x08|[\x0A-\x0D]|"|\\/g, function (value) {
return "\\" + replace[value];
});
};
defn = function (name, value) {
if (d.createElementNS) {
script = d.createElementNS('http://www.w3.org/1999/xhtml', 'script');
} else {
script = d.createElement('script');
}
script.type = 'text/javascript';
script.appendChild(d.createTextNode(toString(name, value)));
d.documentElement.appendChild(script);
d.documentElement.removeChild(script);
};
} catch (e) {
replace = function (value) {
var replace = {
"\x0A": "\\n",
"\x0D": "\\r"
};
return value.replace(/"/g, '""').replace(/\n|\r/g, function (value) {
return replace[value];
});
};
defn = (this.execScript ?
function (name, value) {
that.execScript(toString(name, value), 'VBScript');
} : function (name, value) {
eval(toString(name, value).substring(6));
});
}
defn(name, value);
}
--------------------华丽分割线-----------------------------