- 浏览: 103735 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
sohighthesky:
写的不错,为什么 没有新文章了呢?
自己做的mini-yui和弹出对话框 -
yanlp:
受益匪浅,解决了俺一个大问题,非常非常之感谢。。。
javascript获取元素位置代码总结
y.js
Function.prototype.bind = function(object) { var method = this; return function() { method.apply(object, arguments); } } // Mozilla 1.8 has support for indexOf, lastIndexOf, forEach, filter, map, some, every // http://developer-test.mozilla.org/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (obj, fromIndex) { if (fromIndex == null) { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex; i < this.length; ++i) { if (this[i] === obj) return i; } return -1; }; } // http://developer-test.mozilla.org/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function (obj, fromIndex) { if (fromIndex == null) { fromIndex = this.length - 1; } else if (fromIndex < 0) { fromIndex = Math.max(0, this.length + fromIndex); } for (var i = fromIndex; i >= 0; --i) { if (this[i] === obj) return i; } return -1; }; } // http://developer-test.mozilla.org/docs/Core_JavaScript_1.5_Reference:Objects:Array:forEach if (!Array.prototype.forEach) { Array.prototype.forEach = function (f, obj) { var l = this.length; // must be fixed during loop... see docs for (var i = 0; i < l; ++i) { f.call(obj, this[i], i, this); } }; } // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter if (!Array.prototype.filter) { Array.prototype.filter = function (f, obj) { var l = this.length; // must be fixed during loop... see docs var res = []; for (var i = 0; i < l; ++i) { if (f.call(obj, this[i], i, this)) { res.push(this[i]); } } return res; }; } // http://developer-test.mozilla.org/docs/Core_JavaScript_1.5_Reference:Objects:Array:map // 原数组有多少元素,返回的map也有多少个元素 if (!Array.prototype.map) { Array.prototype.map = function (f, obj) { var l = this.length; // must be fixed during loop... see docs var res = new Array(l); for (var i = 0; i < l; ++i) { res[i] = f.call(obj, this[i], i, this); } return res; }; } // http://developer-test.mozilla.org/docs/Core_JavaScript_1.5_Reference:Objects:Array:some if (!Array.prototype.some) { Array.prototype.some = function (f, obj) { var l = this.length; // must be fixed during loop... see docs for (var i = 0; i < l; i++) { if (f.call(obj, this[i], i, this)) { return true; } } return false; }; } // http://developer-test.mozilla.org/docs/Core_JavaScript_1.5_Reference:Objects:Array:every if (!Array.prototype.every) { Array.prototype.every = function (f, obj) { var l = this.length; // must be fixed during loop... see docs for (var i = 0; i < l; i++) { if (!f.call(obj, this[i], i, this)) { return false; } } return true; }; } Array.prototype.contains = function (obj) { return this.indexOf(obj) != -1; }; Array.prototype.copy = function (obj) { return this.concat(); }; Array.prototype.insertAt = function (obj, i) { this.splice(i, 0, obj); }; Array.prototype.insertBefore = function (obj, obj2) { var i = this.indexOf(obj2); if (i == -1) this.push(obj); else this.splice(i, 0, obj); }; Array.prototype.removeAt = function (i) { this.splice(i, 1); }; Array.prototype.remove = function (obj) { var i = this.indexOf(obj); if (i != -1) this.splice(i, 1); }; /***************** String ******************/ if (!String.prototype.trim) { String.prototype.trim = function() { return this.replace(/^\s*|\s*$/g, ""); }; } if (!String.prototype.replaceAll) { String.prototype.replaceAll = function(from, to) { return this.replace(new RegExp(from, 'gm'), to); } } /** * 取随机整数 * @param {Object} n 最大整数 */ Math.randomInt = function(n) { return Math.floor(Math.random() * (n + 1)); } var Y, YB, YD, YE; if( !Y ) { Y = { xxxx: [], debug: true, //测试log方法开关,发布时一般设置为false $: function(elm, doc) { //简化,只接受和返回单个元素 doc = doc || document; if( elm && typeof elm === "string" ) { return doc.getElementById( elm ); } return elm; }, // 把字符串中 ${xxx} 替换成定义好的字符串, o是替换映射 strMerge: function(s, o) { return s.replace( /\$\{(\w+)\}/g, function( wholeWord, token ) { if( o[token] != undefined ) { return o[token]; } else { return wholeWord; } } ); }, c$: function( type, id, className, doc ) { doc = doc || document; var e = doc.createElement( type ); if( id ) { e.id = id }; if( className ) { e.className = className }; return e; }, getTime: function() { var d = new Date(); return d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds(); }, isString: function(o) { return typeof o === "string"; }, isArray: function( o ) { return Object.prototype.toString.call(o) === "[object Array]"; }, //得到一个js文件所在目录 scriptPath: function(fileName, doc) { fileName = fileName || "y.js"; doc = doc || document; var scriptElms = doc.getElementsByTagName( "script" ); for(var i=0, _l=scriptElms.length; i<_l; ++i) { var ssrc = scriptElms[i].src; if( ssrc ) { var pos = ssrc.indexOf( fileName ); if( pos > -1 ) { // return elements[i].src.substring(0, elements[i].src.lastIndexOf('/') + 1); return ssrc.substring( 0, ssrc.lastIndexOf("/") + 1 ); //参考kindEditor } } } return ""; }, extend: function (destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; }, deepExtend: function (destination, source) { for (var property in source) { var copy = source[property]; if ( destination === copy ) continue; if ( typeof copy === "object" ){ destination[property] = arguments.callee( destination[property] || {}, copy ); } else{ destination[property] = copy; } } return destination; }, log: function( msg, elm ) { if( !Y.debug ) { return; } if( window.console ) { window.console.debug(msg); } else { if( !elm ) { elm = "yLog"; } elm = Y.$(elm); if( !elm ) { var wrapElm = Y.c$( "div", "yLogWrap" ); wrapElm.style.cssText = "position:absolute;right:10px;top:200px;width:280px;border:1px dashed #585858;padding:10px;background:#eee;color:#222;font-size:12px;"; wrapElm.innerHTML = '<div style="border-bottom: 1px #585858 dashed;padding-bottom:5px;text-align:center;" ><input type="button" value="清空log" onclick="Y.$(\'yLog\').innerHTML=\'\'" /></div><div id="yLog" style="width:280px;height:300px;overflow:auto;"></div>'; document.body.appendChild( wrapElm ); } elm = Y.$("yLog"); elm.innerHTML = (elm.innerHTML?elm.innerHTML+"<br />":"") + msg; } } }; // 判断浏览器类型 Y.ua = function() { var ua = navigator.userAgent.toLowerCase(), s, o = {}; if( s=ua.match(/msie ([\d.]+)/) ) { o.ie = true; o.info = "ie"; } else if( s=ua.match(/firefox\/([\d.]+)/) ) { o.ff = true; o.info = "ff"; } else if( s=ua.match(/chrome\/([\d.]+)/) ) { o.chrome = true; o.info = "chrome"; } else if( s=ua.match(/opera.([\d.]+)/) ) { o.opera = true; o.info = "opera"; } else if( s=ua.match(/version\/([\d.]+).*safari/) ) { o.safari = true; o.info = "safari"; } if( s && s[1] ) { o.version = parseFloat( s[1] ); } else { o.version = 0; } o.info = (o.info?o.info:"") + "_" + o.version; o.isQMode = document["compatMode"] == "BackCompat" || document["compatMode"] == "QuirksMode"; //是否是怪异模式下 return o; }(); /* Y.func = (function(){ var slice = Array.prototype.slice; return { bind: function( func, thisp ) { var args = slice.call(arguments, 2); return function() { return func.apply(thisp, args.concat(slice.call(arguments))); } }, bindAsEventListener: function( func, thisp ) { var args = slice.call(arguments, 2); return function(event) { return func.apply(thisp, [E.fixEvent(event)].concat(args)); //TODO! 有错误! } } }; })(); */ /* Y.Region = function(t, r, b, l) { this.top = t; this.y = t; this[1] = t; this.right = r; this.bottom = b; this.left = l; this.x = l; this[0] = l; this.width = this.right - this.left; this.height = this.bottom - this.top; }; */ (function() { var document = window.document, documentElement = document.documentElement, isIE = Y.ua.ie, isSafari = Y.ua.safari, bver = Y.ua.version, isQMode=Y.ua.isQMode; var propertyCache = {}; var styleFloat = isIE ? "styleFloat" : "cssFloat"; // 下面是atrribute的转换,满足条件的是w3c标准,不满足条件的是IE<8的情况 var ELM_ATTRS_ESCAPE = documentElement.hasAttribute?{"htmlFor": "for", "className": "class"}:{ "for": "htmlFor", "class": "className"}; // 这里全部是class的string操作。不涉及到元素,是私有的 var classStrOpt = { // 判断myClassName中是否有testClassName这个class, testClassName只能是一个className,不能是多个class用空格隔开组成的string // 参数都是string类型 hasClass: function( myClassName, testClassName ) { return myClassName && myClassName.split(/\s+/).contains( testClassName ); }, // testClassNames可以是多个class用空格隔开组成的string,判断必须都含有才返回true hasClasses: function( myClassName, testClassNames ) { if( myClassName && testClassNames ) { var myClassNameArray = myClassName.split(/\s+/); var testClassNameArray = testClassNames.split(/\s+/); for(var i=0; i<testClassNameArray.length; ++i) { if( !myClassNameArray.contains( testClassNameArray[i] ) ) { return false; } } return true; } return false; }, // 把 myClassName (string) 中含有的class都删除并返回处理之后的string,参数classNames可以是多个class用空格组成的string, // 如果 classNames=undefined 也就是没有设置这个参数,则返回空串表明全部删除 removeClass: function( myClassName, classNames ) { if( myClassName && classNames !== undefined) { var elmClassArray = myClassName.split(/\s+/); var ret = []; var toRemoveClassArray = classNames ? classNames.split(/\s+/) : []; for( var i=0, n=elmClassArray.length; i<n; ++i ) { if( !toRemoveClassArray.contains( elmClassArray[i] ) ) { ret.push( elmClassArray[i] ); } } return ret.join( " " ); } return ""; }, // 在 myClassName (string) 基础上增加class都并返回处理之后的string,参数classNames可以是多个class用空格组成的string, addClass: function( myClassName, classNames ) { myClassName = myClassName || ""; if( classNames ) { var classArray = classNames.split(/\s+/); var myClassArray = myClassName.split(/\s+/); var change = false; for( var i=0, n=classArray.length; i<n; ++i ) { if( !myClassArray.contains( classArray[i] ) ) { myClassArray.push( classArray[i] ); change = true; } } if( change ) { myClassName = myClassArray.join( " " ); } } return myClassName; }, // 把 myClassName 中的 classNames 替换成 newClassNames // classNames 和 newClassNames 都可以是多个class用空格组成的string, replaceClass: function( myClassName, classNames, newClassNames ) { myClassName = this.removeClass( myClassName, classNames ); myClassName = this.addClass( myClassName, newClassNames ); return myClassName; } }; Y.Region = function(t, r, b, l) { this.top = t; this.y = t; this[1] = t; this.right = r; this.bottom = b; this.left = l; this.x = l; this[0] = l; this.width = this.right - this.left; this.height = this.bottom - this.top; }; Y.dom = { getHead: function(doc) { doc = doc || document; return doc.getElementsByTagName( "head" )[0]; }, getBody: function(doc) { doc = doc || document; return doc.body; }, // 得到元素或者window的 document对象 getDoc: function(elm) { return elm.ownerDocument || elm.document; }, appendToBody: function(elm, doc) { doc = doc || document; doc.body.appendChild( elm ); }, // 可到页面的clientWidth, clientHeight getViewportWH: function(win) { //只读值,只能get,不能set win = win || window; var doc = win.document; var width = win.self.innerWidth, height = win.self.innerHeight // Safari , mode = document.compatMode; if(mode || isIE) { // IE, Gecko, Opera if( mode == "BackCompat" ) { // Quirks mode //if( isQMode ) { // Quirks mode width = doc.body.clientWidth; height = doc.body.clientHeight; } else { var docElm = doc.documentElement; width = docElm.clientWidth; height = docElm.clientHeight; } } return {w: width, h:height}; }, // 得到document的宽高 getDocumentWH: function(doc) { doc = doc || document; var scrollWidth, scrollHeight; //if( document.compatMode == "BackCompat" || isSafari ) { if( isQMode || isSafari ) { scrollWidth = doc.body.scrollWidth; scrollHeight = doc.body.scrollHeight; } else { var docElm = doc.documentElement; scrollWidth = docElm.scrollWidth; scrollHeight = docElm.scrollHeight; } var viewWH = Y.dom.getViewportWH(); return { w: Math.max(scrollWidth, viewWH.w ), h: Math.max(scrollHeight, viewWH.h ) }; }, getDocumentScrollLeft: function(doc) { doc = doc || document; return Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft); }, getDocumentScrollTop: function(doc) { doc = doc || document; return Math.max(doc.documentElement.scrollTop, doc.body.scrollTop); }, // 返回 [x, y] getXY: function() { //getXY得到的是元素border左上角开始的xy坐标 if( document.documentElement.getBoundingClientRect ) { //IE的方式,ff3开始引入 return function(node) { var fl = Math.floor; var box = node.getBoundingClientRect(); var doc = node.ownerDocument; var docElm = doc.documentElement; var scrollLeft = Y.dom.getDocumentScrollLeft(doc); var scrollTop = Y.dom.getDocumentScrollTop(doc); var xy = [ fl(box.left), fl(box.top) ]; if(isIE && bver<8) { // IE < 8 : viewport off by 2 var off1 = 2, off2 = 2; //var mode = doc.compatMode; var bLeft = Y.dom.getComputedStyle( docElm, "borderLeftWidth" ); var bTop = Y.dom.getComputedStyle( docElm, "borderTopWidth" ); // 用YAHOO.util.Dom.getComputedStyle 会计算出IE的这两个值是2px(某些情况下),我这里得到的是medium值 if( bver === 6 ) { // IE 6 //if( mode !== "BackCompat" ) { if( !isQMode ) { //非quirks模式 off1 = 0; off2 = 0; } } //if( mode === "BackCompat" ) { if( isQMode ) { if( bLeft !== "medium" ) { off1 = parseInt(bLeft, 10); } if (bTop !== "medium") { off2 = parseInt(bTop, 10); } } xy[0] -= off1; xy[1] -= off2; } if ((scrollTop || scrollLeft)) { xy[0] = fl( xy[0] + scrollLeft ); xy[1] = fl( xy[1] + scrollTop ); } return xy; } } else { return function(node) { // ff2, safari: manually calculate by crawling up offsetParents var xy = [ node.offsetLeft, node.offsetTop ]; var scrollLeft = Y.dom.getDocumentScrollLeft(doc); var scrollTop = Y.dom.getDocumentScrollTop(doc); var parentNode = node; while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; } if ((scrollTop || scrollLeft)) { xy[0] = fl( xy[0] + scrollLeft ); //是+还是- ??? //@TODO !!! 到底是怎样??? xy[1] = fl( xy[1] + scrollTop ); } return xy; } } }(), setXY: function( elm, xy ) { elm.style.left = xy[0] + "px"; elm.style.top = xy[1] + "px"; }, setX: function( elm, x ) { elm.style.left = x + "px"; }, setY: function( elm, y ) { elm.style.top = y + "px"; }, getRegion: function(elm) { var xy = Y.dom.getXY( elm ), t = xy[1], r = xy[0] + elm.offsetWidth, b = xy[1] + elm.offsetHeight, l = xy[0]; return new Y.Region(t, r, b, l); }, //是否a是否包含了b contains: function(a, b) { return (this.contains = a.compareDocumentPosition ? function (a, b) { return !!(a.compareDocumentPosition(b) & 16); } : function (a, b) { return a != b && a.contains(b); } )(a, b); }, getComputedStyle: function(elm, styleName) { if( window.getComputedStyle ) { //除了IE之外的浏览器 //Y.log( "window.getComputedStyle=" + window.getComputedStyle ); return elm.ownerDocument.defaultView.getComputedStyle(elm, null)[styleName]; // 基本上相当于 window.getComputedStyle(elm, null)[styleName]; } else if( elm.currentStyle ) { //IE的方式 //Y.log( "elm.currentStyle=" + elm.currentStyle ); return elm.currentStyle[styleName]; // 我这里没有像YUI中那样把medium、color值都计算出来,这里得到的结果没有YUI精确。ie调用该方法得到color值是 #404040 这样的值不是 rgb(64, 64, 64) } }, // css 属性名称转成驼峰式的javascript属性,例如 font-size --> fontSize toCamel: function(property) { var c = propertyCache; function tU(x,l) { return l.toUpperCase(); } return c[property] || (c[property] = property.indexOf('-') === -1 ? property : property.replace( /-([a-z])/gi, tU )); }, // 把css属性转换成标准的javascript属性 cssToJSProp: function(property) { return (property === 'float') ? styleFloat : Y.dom.toCamel( property ); }, // 输入参数可以是 css 属性值例如font-size,也可以是javascript表示的css属性名例如 fontSize getStyle: function() { if (window.getComputedStyle ) { // W3C DOM method 除IE之外的浏览器 return function(elm, property) { property = Y.dom.cssToJSProp(property); var value = elm.style[property], computed; if (!value) { computed = elm.ownerDocument.defaultView.getComputedStyle(elm, null); if (computed) { // test computed before touching for safari value = computed[property]; } } return value; }; } else if (documentElement.currentStyle) { //IE return function(elm, property) { var value; if( property === "opacity" ) { try { // will error if no DXImageTransform value = elm.filters['DXImageTransform.Microsoft.Alpha'].opacity; } catch(e) { try { // make sure its in the document value = elm.filters('alpha').opacity; } catch(err) { } } value = value / 100; } else { property = Y.dom.cssToJSProp(property); value = elm.style[property]; if( !value ) { value = elm.currentStyle ? elm.currentStyle.property : null; } } return value; }; // return function } // else if }(), // getStyle 定义结束 // 参数是 (elm, property, val) property可以是 setStyle: function() { if (isIE) { return function(elm, property, val ) { elm = Y.$( elm ); if( elm ) { if( property === "opacity" ) { if ( Y.isString(elm.style.filter) ) { // in case not appended elm.style.filter = 'alpha(opacity=' + val * 100 + ')'; if (!elm.currentStyle || !elm.currentStyle.hasLayout) { elm.style.zoom = 1; // when no layout or cant tell } } } else { property = Y.dom.cssToJSProp(property); elm.style[property] = val; } } // if elm } // return function } else { // 非IE return function(elm, property, val) { elm = Y.$( elm ); if( elm ) { property = Y.dom.cssToJSProp(property); elm.style[property] = val; } // if elm } // return function } // else 非IE }(), // setStyle function 定义完毕 // props 是一个对象,{ key1: val1, key2:val2 ...... } setStyles: function( elm, props ) { for (var k in props) { Y.dom.setStyle( elm, k, props[k] ); } }, getOpacity: function(elm) { return Y.dom.getStyle( elm, "opacity" ); }, // opacityVal是0.2 这样的小数值 setOpacity: function(elm, opacityVal) { return Y.dom.setStyle( elm, "opacity", opacityVal ); }, // 判断元素的某个class是否存在,参数className不是多个class,是单个 // elm 可以是 HTMLElement, 也可以是string类型 hasClass: function( elm, className ) { return elm && classStrOpt.hasClass( elm.className, className ) ; }, hasClasses: function(elm, classNames) { return elm && classStrOpt.hasClasses( elm.className, classNames ) ; }, // 增加元素class, 参数classNames可以是多个class用空格分开 addClass: function( elm, classNames ) { if( elm ) { elm.className = classStrOpt.addClass( elm.className, classNames ); } }, // 删除元素的class,参数classNames可以是多个class用空格分开, // 如果参数classNames为undefined,也就是不设置这个参数,则该元素的class全部删除 removeClass: function( elm, classNames ) { if( elm ) { elm.className =classStrOpt.removeClass( elm.className, classNames ); } }, //替换元素的class replaceClass: function( elm, classNames, newClassNames ) { if( elm ) { elm.className = classStrOpt.replaceClass( elm.className, classNames, newClassNames ); } }, toggleClass: function( elm, clsName ) { if( Y.dom.hasClasses( elm, clsName ) ) { Y.dom.removeClass( elm, clsName ); } else { Y.dom.addClass( elm, clsName ); } }, // 可以是 setAttr( elm, string, string ); // 或者 setAttr( elm, properties ); setAttr: function( elm, name, val ) { if( elm ) { name=ELM_ATTRS_ESCAPE[name] || name; elm.setAttribute(name, val); } }, setAttrs: function( elm, props ) { for( var key in props ) { Y.dom.setAttr( elm, key, props[key] ); } }, getAttr: function( elm, name) { if(elm) { name = ELM_ATTRS_ESCAPE[name] || name; return elm.getAttribute( name ); } return null; }, removeAttr: function( elm, name) { if( elm ) { name = ELM_ATTRS_ESCAPE[name] || name; elm.removeAttribute( name ); } }, removeElm: function( elm ) { if( elm && elm.parentNode ) { return elm.parentNode.removeChild( elm ); } }, // 得到 iframe 的本站域名的最顶层window (不跨 frameset框架,不跨域名) // 用的很少 getSelfTopWin: function( win ) { win = win || window; while( win.parent && win.parent != win ) { try { if( win.parent.document.domain != document.domain ) break; if( win.parent.document.getElementsByTagName( 'frameset' ).length > 0 ) break; } catch( e ) { break; } win = win.parent; } // while return win; } }; // Y.dom = 结束 })(); //Y.dom定义作用域 (function() { // Y.event定义作用域开始 var isIE = Y.ua.ie, isSafari = Y.ua.safari, bver = Y.ua.version; var readyList = [], readyBound = false, isReady = false ; var doReady = function() { //Y.xxxx.push( Y.getTime() + " doReady执行了!" ); if( !isReady ) { isReady = true; if( readyList ) { for(var i=0, _l=readyList.length; i<_l; ++i) { //readyList[i].call( document ); //TODO 不以document为this域 readyList[i](); } readyList = null; } } }; var bindReady = function() { if ( readyBound ) { //确保只bind一次ready return; } readyBound = true; // Mozilla, Opera and webkit nightlies currently support this event if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", function() { document.removeEventListener( "DOMContentLoaded", arguments.callee, false ); doReady(); }, false ); } else if ( document.attachEvent ) { // If IE event model is used // ensure firing before onload, // maybe late but safe also for iframes document.attachEvent("onreadystatechange", function(){ if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", arguments.callee ); doReady(); } }); // If IE and not an iframe // continually check to see if the document is ready if ( document.documentElement.doScroll && window == window.top ) (function(){ if ( isReady ) return; try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch( error ) { setTimeout( arguments.callee, 0 ); return; } // and execute any waiting functions doReady(); })(); } //Y.event.add(window, "load", doReady); // 是否这一行可以去除了! 呵呵 @TODO 因为总是绑定了 _load 方法 }; // bindReady() var listeners = []; var unloadListeners = []; var _calcContext = function( elm, obj, overrideContext ) { var context = elm; if (overrideContext) { if (overrideContext === true) { context = obj; } else { context = overrideContext; } } return context; }; //创建wrapper方法并且cache保存 var createWrapper = function(elm, sType, fn, obj, overrideContext, bCapture) { var context = _calcContext( elm, obj, overrideContext ); // wrap the function so we can return the obj object when // the event fires; var wrappedFn = function(e) { return fn.call(context, Y.event.getEvent(e, elm), obj); //TODO obj是否需要判断是否存在 }; var li = [elm, sType, fn, wrappedFn, context, obj, overrideContext]; listeners.push( li ); return wrappedFn; }; var dealUnloadEventRemove = function(elm, fn) { if( !fn || !fn.call ) { unloadListeners = []; } else { for (i=unloadListeners.length-1; i>-1; i--) { var li = unloadListeners[i]; if( li && li[0] == elm && li[1] == fn ) { unloadListeners.splice(i, 1); return; } } } } var _getCacheIndex = function(elm, sType, fn ) { for (var i=0, l=listeners.length; i<l; i=i+1) { var li = listeners[i]; if ( li && ( li[2] == fn || typeof fn === "undefined" ) && li[0] == elm && li[1] == sType ) { return i; } } return -1; }; var _load = function(e) { //Y.xxxx.push( Y.getTime() + " _load执行了!" ); doReady(); //TODO 可能还需要测试! } var _unload = function(e) { var YE = Y.event, i, j, _len, li, ul=unloadListeners.slice(); var xx = []; for( i=0, _len=unloadListeners.length; i<_len; ++i ) { li = ul[i]; if( li ) { var context = _calcContext( li[0], li[2], li[3] ); // [elm, fn, obj, overrideContext]; li[1].call(context, Y.event.getEvent(e, li[0]), li[2]); xx.push( "unload事件触发:" + li ); ul[i] = null; } } ul = null; unloadListeners = null; if (listeners) { for (j=listeners.length-1; j>-1; j--) { li = listeners[j]; if (li) { xx.push( "自动删除事件:" + li ); YE.remove(li[0], li[1], li[2], j); } } li = null; listeners = null; } YE._removeSimple(window, "unload", _unload); alert( "_unload结尾!" + xx.length + "\n" + xx.join( "\n" ) ); }; Y.event = { getEvent: function(ev, boundEl) { return ev || window.event; }, add: function(elm, sType, fn, obj, overrideContext, bCapture) { var elm1 = Y.$( elm ); //alert( "elm=" + elm.id + "," + elm.tagName ); if( !elm1 ) { if( !isReady ) { //alert( "!isReady,所以到这里来了1" ); //TODO Y.event.addReady( function() { Y.event.add( elm, sType, fn, obj, overrideContext, bCapture ); } ); //检验是否isReady变量设置正确! } else { //alert( "isReady,所以到这里来了2, elm=" + elm ); //TODO } return; } elm = elm1; if ("unload" == sType && obj !== this) { unloadListeners[unloadListeners.length] = [elm, fn, obj, overrideContext]; return; } var wrappedFn = createWrapper(elm, sType, fn, obj, overrideContext, bCapture); try { this._addSimple(elm, sType, wrappedFn, bCapture); } catch(ex) { // handle an error trying to attach an event. If it fails // we need to clean up the cache this.remove(elm, sType, fn); return; } }, purgeElement: function(elm, sType) { elm = Y.$( elm ); if( elm ) { var i = _getCacheIndex( elm, sType ); while( i >= 0 ) { this.remove( elm, sType, null, i ); i = _getCacheIndex( elm, sType ); } } }, remove: function(elm, sType, fn) { elm = Y.$( elm ); var cacheItem; if( !elm ) { return; } if( "unload" == sType ) { dealUnloadEventRemove( elm, fn ); return; } var index = arguments[3]; //隐藏参数 var _b = ("undefined" === typeof index); //表明是否没有定义隐藏参数 =true表示没有定义隐藏参数 if ( _b && (!fn || !fn.call) ) { //如果没有定义隐藏参数,并且fn没有定义或者不是函数 this.purgeElement( elm, sType ); return; } if( _b ) { // 表明是否没有定义隐藏参数 =true表示没有定义隐藏参数 index = _getCacheIndex(elm, sType, fn); } if (index >= 0) { cacheItem = listeners[index]; } if (!elm || !cacheItem) { return; } try { this._removeSimple(elm, sType, cacheItem[3], false); } catch(ex) { } delete listeners[index][3]; delete listeners[index][2]; listeners.splice(index, 1); }, _addSimple: function () { if (window.addEventListener) { return function(elm, sType, fn, capture) { elm.addEventListener(sType, fn, (capture)); }; } else if (window.attachEvent) { return function(elm, sType, fn, capture) { elm.attachEvent("on" + sType, fn); }; } else { return function(elm, sType, fn, capture){ elm["on" + sType] = fn; }; } }(), _removeSimple: function() { if (window.removeEventListener) { return function (elm, sType, fn, capture) { elm.removeEventListener(sType, fn, (capture)); }; } else if (window.detachEvent) { return function (elm, sType, fn) { elm.detachEvent("on" + sType, fn); }; } else { return function(){ elm["on" + sType] = null; }; } }(), addReady: function(fn, obj, overrideContext) { bindReady(); var thisp = window; if( overrideContext ) { if (overrideContext === true) { thisp = obj; } else { thisp = overrideContext; } } if ( isReady ) { //alert( "isReady====&" + isReady ); fn.call( thisp, obj ); } else { readyList.push( function() { fn.call(thisp, obj); } ); } }, getPageX: function(ev) { var x = ev.pageX; if (!x && 0 !== x) { x = ev.clientX || 0; if( isIE ) { x += Y.dom.getDocumentScrollLeft(); } } return x; }, getPageY: function(ev) { var y = ev.pageY; if (!y && 0 !== y) { y = ev.clientY || 0; if( isIE ) { y += Y.dom.getDocumentScrollTop(); } } return y; }, getXY: function(ev) { return [this.getPageX(ev), this.getPageY(ev)]; }, stopEvent: function(ev) { this.stopPropagation(ev); this.preventDefault(ev); }, stopPropagation: function(ev) { if (ev.stopPropagation) { ev.stopPropagation(); } else { ev.cancelBubble = true; } }, preventDefault: function(ev) { if (ev.preventDefault) { ev.preventDefault(); } else { ev.returnValue = false; } }, // 禁止在element上的右键菜单, elm可以是document preventContextMenu: function(elm) { if( !elm ) { elm = document; } else { elm = Y.$( elm ); } if( elm ) { this.add( elm, "contextmenu", Y.event.preventDefault ); } }, getTarget: function(ev) { var t = ev.target || ev.srcElement; try { if( t && 3 == t.nodeType ) { // text node 返回父节点 return t.parentNode; } } catch(e) {} return t; } }; // Y.event定义 // patch for ff,这样在页面全部载入完全之后,还是可以调用addReady方法,至少触发一次domready事件把isReady设置成true! /* if ( document.addEventListener ) { //yadan Y.event.addReady( function() {} ); } */ Y.event._addSimple( window, "load", _load ); Y.event._addSimple( window, "unload", _unload ); })(); // Y.event定义作用域结束 YB=Y.ua; YE=Y.event; YD = Y.dom; //赋值方便的全局变量 } // 最开始最顶层的 if
ysdlg.js
var YDLG; (function() { var YD = Y.dom, YE=Y.event, YB=Y.ua; var cover, coverShim; var _existDlgs = {}; var _getExistDlg = function( id ) { return _existDlgs[id]; }; var _removeExistDlg = function( id ) { _existDlgs[id] = null; }; var _setExistDlg = function(id, sdlg) { _existDlgs[id] = sdlg; }; var getZIndex = function() { return Y.sdlg.cfg.zIndex++; } var _urlAddUuid = function(url) { if( url.indexOf( "?" ) > -1 ) { return url + "&uuid=" + new Date().getTime(); } else { return url + "?uuid=" + new Date().getTime(); } }; Y.sdlgObj=function() { }; var Drag = { obj: null, //被拖拽的box ghost: null, //拖拽的ghost层 cancel: function( head ) { YE.remove( head, "mousedown" ); }, // dragMode = 0/undefined 代表用ghost层拖动 =1代表直接拖动 // dragRestrict = 0 /undefined 代表不受浏览器视窗限制, =1代表在浏览器视窗内拖动 init: function( head, box, dragMode, dragRestrict ) { YE.add( head, "mousedown", Drag.start ); //为什么???????????????????????????????????????????? //head.onmousedown = Drag.start; head.obj = box; if( isNaN(parseInt(box.style.left)) ) { box.style.left = "0px" ; } if( isNaN(parseInt(box.style.top)) ) { box.style.top = "0px" ; } // 挂上空Function,初始化这几个成员,在Drag.init被调用后才帮定到实际的函数,可以参照draggable里面的内容 box.onDragStart = new Function(); box.onDragEnd = new Function(); box.onDrag = new Function(); box.dragMode = dragMode; box.dragRestrict = dragRestrict; //Y.log( "box.dragMode=" + box.dragMode ); }, start: function (ev) { //alert( "this=" + this + ",this.className=" + this.className + ",\nthis.init=" + this.init ); var box = Drag.obj = this.obj; //这个this是head元素 //alert( "box=" + box ); ev = Drag.fixE( ev ); if( ev.which != 1 ) { //只管左键 return true; } box.onDragStart(); //开始拖拽之前的钩子 box.lastMouseX = ev.clientX; box.lastMouseY = ev.clientY; if( !box.dragMode ) { //代表用ghost层拖动 ghost = Y.c$( "div" ); ghost.style.cssText = "position:absolute;left:" + box.style.left + ";top:" + box.style.top + ";width:" + box.offsetWidth + "px;" + ";height:" + box.offsetHeight + "px;background:#D2D9F7;border:#485FDF 2px dashed;z-index:" + (box.style.zIndex+1) ; YD.setOpacity( ghost, .5 ); YD.appendToBody( ghost ); } YE.add( document, "mouseup", Drag.end ); //YE.add( document, "mousemove", Drag.drag, null, false, true ); YE.add( document, "mousemove", Drag.drag ); return false; }, drag: function( ev ) { ev = Drag.fixE( ev ); if( ev.which != 1 ) { //只管左键, google源代码是 event.which == 0 return Drag.end(); } window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); var box = Drag.obj; var _clientX = ev.clientX; var _clientY = ev.clientY; if( box.lastMouseX == _clientX && box.lastMouseY == _clientY ) { return false; } // 刚才Element的坐标 var moevObj = !box.dragMode ? ghost:box ; //被移动的物件 var _lastX = parseInt(moevObj.style.left); var _lastY = parseInt(moevObj.style.top); var newX, newY; newX = _lastX + _clientX - box.lastMouseX; newY = _lastY + _clientY - box.lastMouseY; moevObj.style.left = newX + "px"; moevObj.style.top = newY + "px"; var shim = box.shim; if( shim ) { shim.style.left = newX + "px"; shim.style.top = newY + "px"; } //Y.log( "_clientXY=[" + _clientX + "," + _clientY + "],newXY=[" + newX + "," + newY + "]" ); // box.lastMouseX = _clientX; box.lastMouseY = _clientY; //@TODO 更改 增加拖动模式和判断限制 box.onDrag( newX, newY ); YE.stopEvent( ev ); return false; }, end: function (ev) { ev = Drag.fixE( ev ); YE.remove( document, "mouseup", Drag.end ); YE.remove( document, "mousemove", Drag.drag ); var box = Drag.obj; if( !box.dragMode ) { //代表用ghost层拖动 box.style.left = ghost.style.left; box.style.top = ghost.style.top; YD.removeElm( ghost ); ghost = null; } var _onDragEndFuc = Drag.obj.onDragEnd(); // 拖拽完毕,obj清空 Drag.obj = null ; return _onDragEndFuc; }, fixE: function (ev) { if (typeof ev == "undefined") { ev = window.event; } if (typeof ev.layerX == "undefined") { ev.layerX = ev.offsetX; } if (typeof ev.layerY == "undefined") { ev.layerY = ev.offsetY; } if (typeof ev.which == "undefined") { ev.which = ev.button; } return ev; } }; Y.sdlgObj.prototype.init = function() { if( this.xbtn ) { //alert( "增加了xbtn的click事件" ); var id = this.id; YE.add( this.xbtn, "mousedown", function() { Y.sdlg.close( id ) } ); //this.xbtn.onclick= function() { alert('xxxxxxxxxxxxxxx'); }; } if( !this.noDrag ) { //拖动事件 if( this.shim ) { this.root.shim = this.shim; } Drag.init(this.head, this.root, this.dragMode, this.dragRestrict); } YE.add( window, "resize", this.resize, this, true ); this.resize(); } Y.sdlgObj.prototype.resize = function() { var docWH = YD.getDocumentWH(); if( cover ) { cover.style.width = docWH.w + "px"; cover.style.height = docWH.h + "px"; } if( coverShim ) { coverShim.style.width = docWH.w + "px"; coverShim.style.height = docWH.h + "px"; } } Y.sdlgObj.prototype.close = function() { //alert( "要关闭这个了" + this.id ); this.removeEvent(); YD.removeElm( this.root ); if( cover ) { YD.removeElm( cover ); } if( coverShim ) { YD.removeElm( coverShim ); } if( this.shim ) { YD.removeElm( this.shim ); } this.root = null; this.shim = null; cover = null; //_removeExistDlg( this.id ); } Y.sdlgObj.prototype.removeEvent = function() { YE.remove( this.xbtn, "mousedown" ); if( !this.noDrag ) { //拖动事件 Drag.cancel(this.head); } } var createCover = function() { if(YB.isIE && YB.version < 7) { coverShim = Y.c$( "iframe" ); coverShim.src = "about:blank"; YD.setStyles( coverShim, { position: "absolute", border: "none", left: "0px", top: "0px", zIndex: getZIndex() } ); YD.setOpacity( coverShim, 0 ); YD.appendToBody( coverShim ); } cover = Y.c$( "div" ); var cfg = Y.sdlg.cfg; YD.setStyles( cover, { width: "100%", height: "100%", position: "absolute", left: "0px", top: "0px", zIndex: getZIndex(), opacity: cfg.coverOpacity, backgroundColor: cfg.coverBackColor } ); YD.appendToBody( cover ); }; var ap = function(a, b) { a.appendChild( b ); }; // 必须参数 id // 配置参数 className(不能是class,IE会出错), w, h, l, t, (width/height/left/top), title, url, urlNoCache, noDrag, noResize, autoScroll(自动滚动), cover, dragRestrict, dragMode // 返回增加了 linkFrameId resizeAreaId bodyId headId xbtnId var createSdlg = function( vars ) { var w = vars.w || 400, h = vars.h || 0 ; //h如果不设置,默认值0代表自动高度 var winViewWH = YD.getViewportWH(), //window的可视区宽高 winDocScrollLT = {l:YD.getDocumentScrollLeft(), t:YD.getDocumentScrollTop()}; //window的滚动left top var hAuto = false; if( !h ) { hAuto = true; h = 300; } var t = vars.t?vars.t+winDocScrollLT.t : Math.floor( Math.max( winDocScrollLT.t + (winViewWH.h-h-20)/2, 0 )) ; var l = vars.l?vars.l+winDocScrollLT.l : Math.floor( Math.max( winDocScrollLT.l + (winViewWH.w-w-20)/2, 0 ) ); var type = vars.type || "default"; var o; if( "default" == type ) { //分支开始,留待扩展 var N=null; o = new Y.sdlgObj(); if( vars.cover ) { createCover(); } if(YB.isIE && YB.version < 7) { //IE 6 创建shimIFrame o.shim = Y.c$( "iframe" ); o.shim.src = "about:blank"; YD.setStyles( o.shim, { position: "absolute", border: "none", left: l + "px", top: t + "px" } ); YD.appendToBody( o.shim ); } o.id = vars.id; o.noDrag = vars.noDrag; o.dragRestrict = vars.dragRestrict; o.dragMode = vars.dragMode; o.noResize = vars.noResize; o.autoScroll = vars.autoScroll; o.root = Y.c$( "div", N, vars.className || "sdlg" ); o.root.ysdlgId = o.id; if( !hAuto ) { YD.setStyle( o.root, "height", h+"px" ); } o.wrap = Y.c$("div", N, "sdlgWrap"); o.box = Y.c$("div", N, "sdlgBox"); o.head = Y.c$("div", N, "sdlgHead"); o.title = Y.c$("div", N, "sdlgTitle"); o.xbtn = Y.c$("div", N, "sdlgXBtn"); o.body = Y.c$("div", N, "sdlgBody"); YD.setStyles( o.root, {position: "absolute", left: l+"px", top: t+"px", width: w+"px", zIndex: getZIndex() } ); ap(o.root, o.wrap); ap(o.wrap, o.box); ap(o.box, o.head); ap(o.head, o.title); ap(o.head, o.xbtn); ap(o.box, o.body); if( vars.title ) { o.title.innerHTML = vars.title; } if( vars.url ) { var src = vars.urlNoCache ? _urlAddUuid(vars.url) : vars.url; o.cntIframe = Y.c$("iframe", N, "sdlgCntIFrame"); o.cntIframe.src = src; o.cntIframe.style.border = "none"; YD.setAttrs( o.cntIframe, { frameborder:"0", width:"100%", height:"100%", scrolling:"auto" } ); ap( o.body, o.cntIframe ); } else { o.body.innerHTML = vars.html || ""; } if( !o.noResize ) { o.resizeArea = Y.c$("div", N, "sdlgResizeArea"); ap(o.wrap, o.resizeArea); } YD.setStyles( o.root, {position: "absolute", left: l+"px", top: t+"px", width: w+"px", zIndex: getZIndex() } ); if( !hAuto ) { //如果不是自动高度 o.root.style.height = h + "px"; } YD.appendToBody( o.root ); //最后把root扩充到body if( !hAuto ) { //如果不是自动高度 o.body.style.height = (h - o.head.offsetHeight) + "px"; } if( o.shim ) { o.shim.style.width = o.root.offsetWidth + "px"; o.shim.style.height = o.root.offsetHeight + "px"; //Y.log( "shime:" + o.shim.style.width + "," + o.shim.style.height ); } o.init(); } // 留待扩展 return o; }; Y.sdlg = { cfg: { zIndex: 2009, //起始zIndex coverOpacity: 0.5, // 遮罩透明度 coverBackColor: "#0ff" // 遮罩颜色 }, // vars的参数 id, class(最外层div的class), type(用什么类型的字符串组装,参见SDLG_HTML定义) render: function( vars ) { if( !vars || !vars.id ) { return; } var o = _getExistDlg( vars.id ) if( o ) { //如果已经存在 alert( vars.id + "的已经存在!" ); return; } var o = createSdlg( vars ); _setExistDlg( vars.id, o ); }, closeAll: function() { for( var k in _existDlgs ) { var v = _existDlgs[k]; this.close( k ); } }, close: function( vars ) { if( !vars ) { this.closeAll(); } var id = Y.isString( vars ) ? vars:vars.id; var sdlg = _getExistDlg( id ); if( sdlg ) { sdlg.close(); } //alert( "delete [" + id + "]的对话框" ); _removeExistDlg( id ); }, closeMySdlg: function( elm ) { var p = elm.parentNode; while( p && !(p.tagName && "div" == p.tagName.toLowerCase() && p.ysdlgId) ) { p = p.parentNode; } //alert( "找到p.ysdlgId=" + p.ysdlgId ); this.close( p.ysdlgId ); return; } }; // Y.sdlg 定义 YDLG = Y.sdlg; })(); //最外层作用域
发表评论
-
javascript取得元素style值的方法
2009-09-18 00:55 1830因为写js经常需要用到访问样式,我们常用的做法是通过 DOM. ... -
Javascript - 全面理解 caller,callee,call,apply (转载)
2009-09-17 03:05 828文章来源 http://www.never-online.n ... -
javascript数据变量类型判断(JS变量是否是数组,是否是函数的判断)
2009-09-17 02:47 3309判断某变量类型,是否是数组,是否是函数。 从YUI2.7、JQ ... -
javascript检测浏览器类型总结(通过useragent判断)
2009-09-17 02:22 30765先看几个useragent,都是 ... -
javascript闭包学习总结
2009-09-17 01:20 1311学习闭包的好文章: 1. 阮一峰: 学习Javascript ... -
javascript获取元素位置代码总结
2009-09-16 18:17 5982阮一峰 http://www.ruanyifeng.com/b ...
相关推荐
压缩JavaScript和CSS文件可以显著减少页面加载时间,"grunt-yui-compressor"就是一个这样的工具,它基于Grunt自动化构建工具,结合Yahoo的YUI Compressor进行代码压缩,帮助开发者高效地处理项目中的前端资源。...
有JAVA版本和.NET版本。 yuicompressor-2.4.2.jar yuicompressor-2.4.7.jar jsZip.exe yuicompressor yui compressor js压缩工具 javascript压缩工具 css压缩工具 ------------------------------------ //压缩...
Locator-Yui 是 YUI 文件定位器插件。它可以与 Locator 组件(from Yahoo! to shift YUI' modules)集成使用,生成 YUI Loader ...已编译的模块则可以通过 express-yui在服务器和客户端中使用。 标签:Locator
npm install yui-compressor ``` 安装完成后,可以使用以下命令对JavaScript或CSS文件进行压缩: ```bash java -jar path/to/yuicompressor.jar --type js input.js -o output.min.js java -jar path/to/yui...
【标题】"yui-yuidoc-yuidoc-50-529-gc631758" 指向的是一个关于 Yahoo User Interface Library (YUI) 和 YUIDoc 的特定版本或修订版。YUI 是一个开源的 JavaScript 库,提供了一系列模块化的工具,用于构建富有交互...
在本场景中,"dwr-yui实现分页"指的是利用DWR和YUI库来实现网页的分页功能。 分页是Web应用程序中常见的功能,尤其是处理大量数据时,它可以提高用户体验,避免一次性加载过多内容导致页面加载慢或者浏览器崩溃。...
这个压缩包特别提到了 "YUI 3 Source",意味着它包含了YUI 3的完整源代码,对于学习和理解YUI 3的内部工作原理,以及进行定制化开发非常有帮助。 ### YUI 3 知识点 1. **模块化设计**:YUI 3 采用了模块化的架构,...
YUI Compressor - The Yahoo! JavaScript and CSS Compressor The YUI Compressor is a JavaScript compressor which, in addition to removing comments and white-spaces, obfuscates local variables using the ...
grunt-yui-compressor 一个使用 YUI Compressor 压缩 JavaScript 和 CSS 文件的插件。 入门 安装模块: npm install grunt-yui-compressor 然后将此行添加到您项目的grunt.js gruntfile 中: grunt . ...
这个插件是基于YUI Compressor,一个由Yahoo开发的开源工具,它能有效地压缩和混淆代码,从而减少文件大小,提升网页加载速度,并降低服务器带宽消耗。 ### 一、Maven插件介绍 Maven是Java领域广泛使用的项目管理...
而YUI-EXT则是对YUI功能的补充,它主要专注于用户界面组件的实现,提供了丰富的UI元素和工具,使得开发者可以快速构建出专业级别的Web应用界面。 在YUI-EXT中,有几个核心概念值得深入理解: 1. **组件...
**Dag-YUI-Compressor** 是一个基于 **Node.js** 的实用工具,它提供了便捷的拖拽上传功能,能够对CSS和JavaScript文件进行压缩。这个工具特别适用于前端开发者,帮助他们在项目开发过程中优化资源加载速度,减小...
yuicompressor-2.4.2.jar yuicompressor-2.4.7.jar jsZip.exe yuicompressor yui compressor js压缩工具 javascript压缩工具 css压缩工具 ------------------------------------ //压缩JS java -jar yuicompressor-...
(尚未稳定)YUI3项目的Yeoman发电机安装sudo npm install -g generator-yui3建立专案yo yui3 awesomeProject.generator-yui3.json 允许您覆盖默认配置{ "project" : "awesomeProject", "lang" : ["fr", "en", "es",...
yui compressor 2.4.6 发布日期:2011-04-15 用例: java -jar yuicompressor-2.4.6.jar myfile.js -o myfile-min.js
es6-module-transpiler-yui-formatter ES6 Module Transpiler Formatter 输出YUI.add()格式概述ES6 模块转换器es6-module-transpiler是一个实验性编译器,它允许您使用当前 ES6 模块语法的子集编写 JavaScript,并将...
选择-yui 使用,请确保获取原生 js 文件... all ( '.yui-chosen' ) . each ( function ( ele ) { ele . plug ( Y . Chosen , { no_results_text : "Nothing found dummy." , disable_search_threshold : 4 , max_s
上述代码中,你需要替换`path/to/`为实际存放YUI库及YUI-Ext库的具体路径。 2. **加载CSS样式文件** ```html <link rel="stylesheet" type="text/css" href="path/to/YUI-Ext/css/file"> ``` 这里列出了一些...
有志于做JAVA职业规划、技术提升的可与我联系,交个朋友~ 本人十余年JAVA从业经验,精通JAVA高可用、分布式、高并发系统架构设计。有志于做JAVA职业规划、技术提升的可与我联系,交个朋友~ 本人十余年JAVA从业经验...