芝麻web文件管理V1.00
编辑当前文件:/home/qrafawbu/rentandbuyrealty.com/mobile/lib/gsap/src/uncompressed/utils/Draggable.js
/*! * VERSION: 0.10.3 * DATE: 2014-05-13 * UPDATES AND DOCS AT: http://www.greensock.com * * Requires TweenLite and CSSPlugin version 1.11.0 or later (TweenMax contains both TweenLite and CSSPlugin). ThrowPropsPlugin is required for momentum-based continuation of movement after the mouse/touch is released (ThrowPropsPlugin is a membership benefit of Club GreenSock - http://www.greensock.com/club/). * * @license Copyright (c) 2008-2014, GreenSock. All rights reserved. * This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, jack@greensock.com */ (window._gsQueue || (window._gsQueue = [])).push( function() { "use strict"; window._gsDefine("utils.Draggable", ["events.EventDispatcher","TweenLite"], function(EventDispatcher, TweenLite) { var _tempVarsXY = {css:{}}, //speed optimization - we reuse the same vars object for x/y TweenLite.set() calls to minimize garbage collection tasks and improve performance. _tempVarsX = {css:{}}, _tempVarsY = {css:{}}, _tempVarsRotation = {css:{}}, _tempEvent = {}, //for populating with pageX/pageY in old versions of IE _doc = document, _docElement = _doc.documentElement || {}, _emptyArray = [], _emptyFunc = function() { return false; }, _RAD2DEG = 180 / Math.PI, _max = 999999999999999, _getTime = Date.now || function() {return new Date().getTime();}, _isOldIE = (_doc.all && !_doc.addEventListener), _renderQueue = [], _lookup = {}, //when a Draggable is created, the target gets a unique _gsDragID property that allows gets associated with the Draggable instance for quick lookups in Draggable.get(). This avoids circular references that could cause gc problems. _lookupCount = 0, _clickableTagExp = /^(?:a|input|textarea|button|select)$/i, _dragCount = 0, //total number of elements currently being dragged _prefix, _isMultiTouching, _lastDragTime = 0, ThrowPropsPlugin, _renderQueueTick = function() { var i = _renderQueue.length; while (--i > -1) { _renderQueue[i](); } }, _addToRenderQueue = function(func) { _renderQueue.push(func); if (_renderQueue.length === 1) { TweenLite.ticker.addEventListener("tick", _renderQueueTick, this, false, 1); } }, _removeFromRenderQueue = function(func) { var i = _renderQueue.length; while (--i > -1) { if (_renderQueue[i] === func) { _renderQueue.splice(i, 1); } } TweenLite.to(_renderQueueTimeout, 0, {overwrite:"all", delay:15, onComplete:_renderQueueTimeout}); //remove the "tick" listener only after the render queue is empty for 15 seconds (to improve performance). Adding/removing it constantly for every click/touch wouldn't deliver optimal speed, and we also don't want the ticker to keep calling the render method when things are idle for long periods of time (we want to improve battery life on mobile devices). }, _renderQueueTimeout = function() { if (!_renderQueue.length) { TweenLite.ticker.removeEventListener("tick", _renderQueueTick); } }, _extend = function(obj, defaults) { var p; for (p in defaults) { if (obj[p] === undefined) { obj[p] = defaults[p]; } } return obj; }, _getDocScrollTop = function() { return (window.pageYOffset != null) ? window.pageYOffset : (_doc.scrollTop != null) ? _doc.scrollTop : _docElement.scrollTop || _doc.body.scrollTop || 0; }, _getDocScrollLeft = function() { return (window.pageXOffset != null) ? window.pageXOffset : (_doc.scrollLeft != null) ? _doc.scrollLeft : _docElement.scrollLeft || _doc.body.scrollLeft || 0; }, //just used for IE8 and earlier to normalize events and populate pageX/pageY _populateIEEvent = function(e, preventDefault) { e = e || window.event; _tempEvent.pageX = e.clientX + _doc.body.scrollLeft + _docElement.scrollLeft; _tempEvent.pageY = e.clientY + _doc.body.scrollTop + _docElement.scrollTop; if (preventDefault) { e.returnValue = false; } return _tempEvent; }, //grabs the first element it finds (and we include the window as an element), so if it's selector text, it'll feed that value to TweenLite.selector, if it's a jQuery object or some other selector engine's result, it'll grab the first one, and same for an array. If the value doesn't contain a DOM element, it'll just return null. _unwrapElement = function(value) { if (!value) { return value; } if (typeof(value) === "string") { value = TweenLite.selector(value); } if (value.length && value !== window && value[0] && value[0].style && !value.nodeType) { value = value[0]; } return (value === window || (value.nodeType && value.style)) ? value : null; }, _checkPrefix = function(e, p) { var s = e.style, capped, i, a; if (s[p] === undefined) { a = ["O","Moz","ms","Ms","Webkit"]; i = 5; capped = p.charAt(0).toUpperCase() + p.substr(1); while (--i > -1 && s[a[i]+capped] === undefined) { } if (i < 0) { return ""; } _prefix = (i === 3) ? "ms" : a[i]; p = _prefix + capped; } return p; }, _setStyle = function(e, p, value) { var s = e.style; if (s[p] === undefined) { p = _checkPrefix(e, p); } if (value == null) { if (s.removeProperty) { s.removeProperty(p.replace(/([A-Z])/g, "-$1").toLowerCase()); } else { //note: old versions of IE use "removeAttribute()" instead of "removeProperty()" s.removeAttribute(p); } } else if (s[p] !== undefined) { s[p] = value; } }, _getComputedStyle = _doc.defaultView ? _doc.defaultView.getComputedStyle : _emptyFunc, _horizExp = /(?:Left|Right|Width)/i, _suffixExp = /(?:\d|\-|\+|=|#|\.)*/g, _convertToPixels = function(t, p, v, sfx, recurse) { if (sfx === "px" || !sfx) { return v; } if (sfx === "auto" || !v) { return 0; } var horiz = _horizExp.test(p), node = t, style = _tempDiv.style, neg = (v < 0), pix; if (neg) { v = -v; } if (sfx === "%" && p.indexOf("border") !== -1) { pix = (v / 100) * (horiz ? t.clientWidth : t.clientHeight); } else { style.cssText = "border:0 solid red;position:" + _getStyle(t, "position", true) + ";line-height:0;"; if (sfx === "%" || !node.appendChild) { node = t.parentNode || _doc.body; style[(horiz ? "width" : "height")] = v + sfx; } else { style[(horiz ? "borderLeftWidth" : "borderTopWidth")] = v + sfx; } node.appendChild(_tempDiv); pix = parseFloat(_tempDiv[(horiz ? "offsetWidth" : "offsetHeight")]); node.removeChild(_tempDiv); if (pix === 0 && !recurse) { pix = _convertToPixels(t, p, v, sfx, true); } } return neg ? -pix : pix; }, _calculateOffset = function(t, p) { //for figuring out "top" or "left" in px when it's "auto". We need to factor in margin with the offsetLeft/offsetTop if (_getStyle(t, "position", true) !== "absolute") { return 0; } var dim = ((p === "left") ? "Left" : "Top"), v = _getStyle(t, "margin" + dim, true); return t["offset" + dim] - (_convertToPixels(t, p, parseFloat(v), v.replace(_suffixExp, "")) || 0); }, _getStyle = function(element, prop, keepUnits) { var rv = (element._gsTransform || {})[prop], cs; if (rv || rv === 0) { return rv; } else if (element.style[prop]) { rv = element.style[prop]; } else if ((cs = _getComputedStyle(element))) { rv = cs.getPropertyValue(prop.replace(/([A-Z])/g, "-$1").toLowerCase()); rv = (rv || cs.length) ? rv : cs[prop]; //Opera behaves VERY strangely - length is usually 0 and cs[prop] is the only way to get accurate results EXCEPT when checking for -o-transform which only works with cs.getPropertyValue()! } else if (element.currentStyle) { rv = element.currentStyle[prop]; } if (rv === "auto" && (prop === "top" || prop === "left")) { rv = _calculateOffset(element, prop); } return keepUnits ? rv : parseFloat(rv) || 0; }, _dispatchEvent = function(instance, type, callbackName) { var vars = instance.vars, callback = vars[callbackName], listeners = instance._listeners[type]; if (typeof(callback) === "function") { callback.apply(vars[callbackName + "Scope"] || instance, vars[callbackName + "Params"] || [instance.pointerEvent]); } if (listeners) { instance.dispatchEvent(type); } }, _getBounds = function(obj, context) { //accepts any of the following: a DOM element, jQuery object, selector text, or an object defining bounds as {top, left, width, height} or {minX, maxX, minY, maxY}. Returns an object with left, top, width, and height properties. var e = _unwrapElement(obj), top, left, offset; if (!e) { if (obj.left !== undefined) { offset = _getOffsetTransformOrigin(context); //the bounds should be relative to the origin return {left: obj.left - offset.x, top: obj.top - offset.y, width: obj.width, height: obj.height}; } left = obj.min || obj.minX || obj.minRotation || 0; top = obj.min || obj.minY || 0; return {left:left, top:top, width:(obj.max || obj.maxX || obj.maxRotation || 0) - left, height:(obj.max || obj.maxY || 0) - top}; } return _getElementBounds(e, context); }, _tempDiv = _doc.createElement("div"), _supports3D = (_checkPrefix(_tempDiv, "perspective") !== ""), // start matrix and point conversion methods... _originProp = _checkPrefix(_tempDiv, "transformOrigin").replace(/^ms/g, "Ms").replace(/([A-Z])/g, "-$1").toLowerCase(), _transformProp = _checkPrefix(_tempDiv, "transform"), _transformCSSProp = _transformProp.replace(/^ms/g, "Ms").replace(/([A-Z])/g, "-$1").toLowerCase(), _point1 = {}, //we reuse _point1 and _point2 objects inside matrix and point conversion methods to conserve memory and minimize garbage collection tasks. _point2 = {}, _hasReparentBug, //we'll set this inside the _getOffset2DMatrix() method after the body has loaded. _getOffsetTransformOrigin = function(e, decoratee) { decoratee = decoratee || {}; if (!e || e === _docElement || !e.parentNode) { return {x:0, y:0}; } var cs = _getComputedStyle(e), v = (_originProp && cs) ? cs.getPropertyValue(_originProp) : "50% 50%", a = v.split(" "), x = (v.indexOf("left") !== -1) ? "0%" : (v.indexOf("right") !== -1) ? "100%" : a[0], y = (v.indexOf("top") !== -1) ? "0%" : (v.indexOf("bottom") !== -1) ? "100%" : a[1]; if (y === "center" || y == null) { y = "50%"; } if (x === "center" || isNaN(parseFloat(x))) { //remember, the user could flip-flop the values and say "bottom center" or "center bottom", etc. "center" is ambiguous because it could be used to describe horizontal or vertical, hence the isNaN(). If there's an "=" sign in the value, it's relative. x = "50%"; } decoratee.x = ((x.indexOf("%") !== -1) ? e.offsetWidth * parseFloat(x) / 100 : parseFloat(x)); decoratee.y = ((y.indexOf("%") !== -1) ? e.offsetHeight * parseFloat(y) / 100 : parseFloat(y)); return decoratee; }, _getOffset2DMatrix = function(e, offsetOrigin, parentOffsetOrigin) { var cs, m, parent, offsetParent, isRoot; if (e === window || !e || !e.parentNode) { return [1,0,0,1,0,0]; } cs = _getComputedStyle(e); m = cs ? cs.getPropertyValue(_transformCSSProp) : e.currentStyle ? e.currentStyle[_transformProp] : "1,0,0,1,0,0"; m = (m + "").match(/(?:\-|\b)[\d\-\.e]+\b/g) || [1,0,0,1,0,0]; if (m.length > 6) { m = [m[0], m[1], m[4], m[5], m[12], m[13]]; } if (offsetOrigin) { parent = e.parentNode; offsetParent = e.offsetParent; isRoot = (parent === _docElement || parent === _doc.body); m[4] = Number(m[4]) + offsetOrigin.x + e.offsetLeft - parentOffsetOrigin.x - (isRoot ? 0 : parent.scrollLeft) + (offsetParent ? parseInt(_getStyle(offsetParent, "borderLeftWidth"), 10) || 0 : 0); m[5] = Number(m[5]) + offsetOrigin.y + e.offsetTop - parentOffsetOrigin.y - (isRoot ? 0 : parent.scrollTop) + (offsetParent ? parseInt(_getStyle(offsetParent, "borderTopWidth"), 10) || 0 : 0); if (!offsetParent && _getStyle(e, "position", cs) === "fixed") { //fixed position elements should factor in the scroll position of the document. m[4] += _getDocScrollLeft(); m[5] += _getDocScrollTop(); } //some browsers (like Chrome 31) have a bug that causes the offsetParent not to report correctly when a transform is applied to an element's parent, so the offsetTop and offsetLeft are measured from the parent instead of whatever the offsetParent reports as. For example, put an absolutely-positioned child div inside a position:static parent, then check the child's offsetTop before and after you apply a transform, like rotate(1deg). You'll see that it changes, but the offsetParent doesn't. So we must sense this condition here (and we can only do it after the body has loaded, as browsers don't accurately report offsets otherwise) and set a variable that we can easily reference later. if (_hasReparentBug === undefined && _doc.body && _transformProp) { _hasReparentBug = (function() { var parent = _doc.createElement("div"), child = _doc.createElement("div"), oldOffsetParent, value; child.style.position = "absolute"; _doc.body.appendChild(parent); parent.appendChild(child); oldOffsetParent = child.offsetParent; parent.style[_transformProp] = "rotate(1deg)"; value = (child.offsetParent === oldOffsetParent); _doc.body.removeChild(parent); return value; }()); } if (parent && parent.offsetParent === e.offsetParent && (!_hasReparentBug || _getOffset2DMatrix(parent).join("") === "100100")) { m[4] -= parent.offsetLeft; m[5] -= parent.offsetTop; } } return m; }, _getConcatenatedMatrix = function(e, invert) { //note: we keep reusing _point1 and _point2 in order to minimize memory usage and garbage collection chores. var originOffset = _getOffsetTransformOrigin(e, _point1), parentOriginOffset = _getOffsetTransformOrigin(e.parentNode, _point2), m = _getOffset2DMatrix(e, originOffset, parentOriginOffset), a, b, c, d, tx, ty, m2, determinant; while ((e = e.parentNode) && e.parentNode && e !== _docElement) { originOffset = parentOriginOffset; parentOriginOffset = _getOffsetTransformOrigin(e.parentNode, (originOffset === _point1) ? _point2 : _point1); m2 = _getOffset2DMatrix(e, originOffset, parentOriginOffset); a = m[0]; b = m[1]; c = m[2]; d = m[3]; tx = m[4]; ty = m[5]; m[0] = a * m2[0] + b * m2[2]; m[1] = a * m2[1] + b * m2[3]; m[2] = c * m2[0] + d * m2[2]; m[3] = c * m2[1] + d * m2[3]; m[4] = tx * m2[0] + ty * m2[2] + m2[4]; m[5] = tx * m2[1] + ty * m2[3] + m2[5]; } if (invert) { a = m[0]; b = m[1]; c = m[2]; d = m[3]; tx = m[4]; ty = m[5]; determinant = (a * d - b * c); m[0] = d / determinant; m[1] = -b / determinant; m[2] = -c / determinant; m[3] = a / determinant; m[4] = (c * ty - d * tx) / determinant; m[5] = -(a * ty - b * tx) / determinant; } return m; }, _localToGlobal = function(e, p, decoratee) { var m = _getConcatenatedMatrix(e), x = p.x, y = p.y; decoratee = (decoratee === true) ? p : decoratee || {}; decoratee.x = x * m[0] + y * m[2] + m[4]; decoratee.y = x * m[1] + y * m[3] + m[5]; return decoratee; }, _localizePoint = function(p, localToGlobal, globalToLocal) { var x = p.x * localToGlobal[0] + p.y * localToGlobal[2] + localToGlobal[4], y = p.x * localToGlobal[1] + p.y * localToGlobal[3] + localToGlobal[5]; p.x = x * globalToLocal[0] + y * globalToLocal[2] + globalToLocal[4]; p.y = x * globalToLocal[1] + y * globalToLocal[3] + globalToLocal[5]; return p; }, _getElementBounds = function(e, context) { var origin, left, right, top, bottom, mLocalToGlobal, mGlobalToLocal, p1, p2, p3, p4; if (e === window) { top = _getDocScrollTop(); left = _getDocScrollLeft(); right = left + (_docElement.clientWidth || e.innerWidth || _doc.body.clientWidth || 0); bottom = top + ((e.innerHeight - 20 < _docElement.clientHeight) ? _docElement.clientHeight : e.innerHeight || _doc.body.clientHeight || 0); //some browsers (like Firefox) ignore absolutely positioned elements, and collapse the height of the documentElement, so it could be 8px, for example, if you have just an absolutely positioned div. In that case, we use the innerHeight to resolve this. } else { origin = _getOffsetTransformOrigin(e); left = -origin.x; right = left + e.offsetWidth; top = -origin.y; bottom = top + e.offsetHeight; } if (e === context) { return {left:left, top:top, width: right - left, height: bottom - top}; } mLocalToGlobal = _getConcatenatedMatrix(e); mGlobalToLocal = _getConcatenatedMatrix(context, true); p1 = _localizePoint({x:left, y:top}, mLocalToGlobal, mGlobalToLocal); p2 = _localizePoint({x:right, y:top}, mLocalToGlobal, mGlobalToLocal); p3 = _localizePoint({x:right, y:bottom}, mLocalToGlobal, mGlobalToLocal); p4 = _localizePoint({x:left, y:bottom}, mLocalToGlobal, mGlobalToLocal); left = Math.min(p1.x, p2.x, p3.x, p4.x); top = Math.min(p1.y, p2.y, p3.y, p4.y); return {left:left, top:top, width:Math.max(p1.x, p2.x, p3.x, p4.x) - left, height:Math.max(p1.y, p2.y, p3.y, p4.y) - top}; }, // end matrix and point conversion methods _isArrayLike = function(e) { return (e.length && e[0] && ((e[0].nodeType && e[0].style && !e.nodeType) || (e[0].length && e[0][0]))) ? true : false; //could be an array of jQuery objects too, so accommodate that. }, _flattenArray = function(a) { var result = [], l = a.length, i, e, j; for (i = 0; i < l; i++) { e = a[i]; if (_isArrayLike(e)) { j = e.length; for (j = 0; j < e.length; j++) { result.push(e[j]); } } else { result.push(e); } } return result; }, _isTouchDevice = (("ontouchstart" in _docElement) && ("orientation" in window)), _touchEventLookup = (function(types) { //we create an object that makes it easy to translate touch event types into their "pointer" counterparts if we're in a browser that uses those instead. Like IE10 uses "MSPointerDown" instead of "touchstart", for example. var standard = types.split(","), converted = ((_tempDiv.onpointerdown !== undefined) ? "pointerdown,pointermove,pointerup,pointercancel" : (_tempDiv.onmspointerdown !== undefined) ? "MSPointerDown,MSPointerMove,MSPointerUp,MSPointerCancel" : types).split(","), obj = {}, i = 7; while (--i > -1) { obj[standard[i]] = converted[i]; obj[converted[i]] = standard[i]; } return obj; }("touchstart,touchmove,touchend,touchcancel")), _addListener = function(element, type, func) { if (element.addEventListener) { element.addEventListener(_touchEventLookup[type] || type, func, false); } else if (element.attachEvent) { element.attachEvent("on" + type, func); } }, _removeListener = function(element, type, func) { if (element.removeEventListener) { element.removeEventListener(_touchEventLookup[type] || type, func); } else if (element.detachEvent) { element.detachEvent("on" + type, func); } }, _onMultiTouchDocumentEnd = function(e) { _isMultiTouching = (e.touches && _dragCount < e.touches.length); _removeListener(e.target, "touchend", _onMultiTouchDocumentEnd); }, _onMultiTouchDocument = function(e) { _isMultiTouching = (e.touches && _dragCount < e.touches.length); _addListener(e.target, "touchend", _onMultiTouchDocumentEnd); }, _parseThrowProps = function(draggable, snap, max, min, factor, forceZeroVelocity) { var vars = {}, a, i, l; if (snap) { if (factor !== 1 && snap instanceof Array) { //some data must be altered to make sense, like if the user passes in an array of rotational values in degrees, we must convert it to radians. Or for scrollLeft and scrollTop, we invert the values. vars.end = a = []; l = snap.length; for (i = 0; i < l; i++) { a[i] = snap[i] * factor; } } else if (typeof(snap) === "function") { vars.end = function(value) { return snap.call(draggable, value) * factor; //we need to ensure that we can scope the function call to the Draggable instance itself so that users can access important values like maxX, minX, maxY, minY, x, and y from within that function. }; } else { vars.end = snap; } } if (max || max === 0) { vars.max = max; } if (min || min === 0) { vars.min = min; } if (forceZeroVelocity) { vars.velocity = 0; } return vars; }, _isClickable = function(e) { //sometimes it's convenient to mark an element as clickable by adding a data-clickable="true" attribute (in which case we won't preventDefault() the mouse/touch event). This method checks if the element is an
,
, or
or has an onclick or has the data-clickable attribute set to true (or any of its parent elements). var data; return (!e || !e.getAttribute || e.nodeName === "BODY") ? false : ((data = e.getAttribute("data-clickable")) === "true" || (data !== "false" && (e.onclick || _clickableTagExp.test(e.nodeName + "")))) ? true : _isClickable(e.parentNode); }, _addPaddingBR, _addPaddingLeft = (function() { //this function is in charge of analyzing browser behavior related to padding. It sets the _addPaddingBR to true if the browser doesn't normally factor in the bottom or right padding on the element inside the scrolling area, and it sets _addPaddingLeft to true if it's a browser that requires the extra offset (offsetLeft) to be added to the paddingRight (like Opera). var div = _doc.createElement("div"), child = _doc.createElement("div"), childStyle = child.style, parent = _doc.body || _tempDiv, val; childStyle.display = "inline-block"; childStyle.position = "relative"; div.style.cssText = child.innerHTML = "width:90px; height:40px; padding:10px; overflow:auto; visibility: hidden"; div.appendChild(child); parent.appendChild(div); _addPaddingBR = (child.offsetHeight + 18 > div.scrollHeight); //div.scrollHeight should be child.offsetHeight + 20 because of the 10px of padding on each side, but some browsers ignore one side. We allow a 2px margin of error. childStyle.width = "100%"; if (!_transformProp) { childStyle.paddingRight = "500px"; val = div.scrollLeft = div.scrollWidth - div.clientWidth; childStyle.left = "-90px"; val = (val !== div.scrollLeft); } parent.removeChild(div); return val; }()), //The ScrollProxy class wraps an element's contents into another div (we call it "content") that we either add padding when necessary or apply a translate3d() transform in order to overscroll (scroll past the boundaries). This allows us to simply set the scrollTop/scrollLeft (or top/left for easier reverse-axis orientation, which is what we do in Draggable) and it'll do all the work for us. For example, if we tried setting scrollTop to -100 on a normal DOM element, it wouldn't work - it'd look the same as setting it to 0, but if we set scrollTop of a ScrollProxy to -100, it'll give the correct appearance by either setting paddingTop of the wrapper to 100 or applying a 100-pixel translateY. ScrollProxy = function(element, vars) { element = _unwrapElement(element); vars = vars || {}; var content = _doc.createElement("div"), style = content.style, node = element.firstChild, offsetTop = 0, offsetLeft = 0, prevTop = element.scrollTop, prevLeft = element.scrollLeft, scrollWidth = element.scrollWidth, scrollHeight = element.scrollHeight, extraPadRight = 0, maxLeft = 0, maxTop = 0, elementWidth, elementHeight, contentHeight, nextNode, transformStart, transformEnd; if (_supports3D && vars.force3D !== false) { transformStart = "translate3d("; transformEnd = "px,0px)"; } else if (_transformProp) { transformStart = "translate("; transformEnd = "px)"; } this.scrollTop = function(value, force) { if (!arguments.length) { return -this.top(); } this.top(-value, force); }; this.scrollLeft = function(value, force) { if (!arguments.length) { return -this.left(); } this.left(-value, force); }; this.left = function(value, force) { if (!arguments.length) { return -(element.scrollLeft + offsetLeft); } var dif = element.scrollLeft - prevLeft, oldOffset = offsetLeft; if ((dif > 2 || dif < -2) && !force) { //if the user interacts with the scrollbar (or something else scrolls it, like the mouse wheel), we should kill any tweens of the ScrollProxy. prevLeft = element.scrollLeft; TweenLite.killTweensOf(this, true, {left:1, scrollLeft:1}); this.left(-prevLeft); if (vars.onKill) { vars.onKill(); } return; } value = -value; //invert because scrolling works in the opposite direction if (value < 0) { offsetLeft = (value - 0.5) | 0; value = 0; } else if (value > maxLeft) { offsetLeft = (value - maxLeft) | 0; value = maxLeft; } else { offsetLeft = 0; } if (offsetLeft || oldOffset) { if (transformStart) { if (!this._suspendTransforms) { style[_transformProp] = transformStart + -offsetLeft + "px," + -offsetTop + transformEnd; } } else { style.left = -offsetLeft + "px"; } if (_addPaddingLeft && offsetLeft + extraPadRight >= 0) { style.paddingRight = offsetLeft + extraPadRight + "px"; } } element.scrollLeft = value | 0; prevLeft = element.scrollLeft; //don't merge this with the line above because some browsers adjsut the scrollLeft after it's set, so in order to be 100% accurate in tracking it, we need to ask the browser to report it. }; this.top = function(value, force) { if (!arguments.length) { return -(element.scrollTop + offsetTop); } var dif = element.scrollTop - prevTop, oldOffset = offsetTop; if ((dif > 2 || dif < -2) && !force) { //if the user interacts with the scrollbar (or something else scrolls it, like the mouse wheel), we should kill any tweens of the ScrollProxy. prevTop = element.scrollTop; TweenLite.killTweensOf(this, true, {top:1, scrollTop:1}); this.top(-prevTop); if (vars.onKill) { vars.onKill(); } return; } value = -value; //invert because scrolling works in the opposite direction if (value < 0) { offsetTop = (value - 0.5) | 0; value = 0; } else if (value > maxTop) { offsetTop = (value - maxTop) | 0; value = maxTop; } else { offsetTop = 0; } if (offsetTop || oldOffset) { if (transformStart) { if (!this._suspendTransforms) { style[_transformProp] = transformStart + -offsetLeft + "px," + -offsetTop + transformEnd; } } else { style.top = -offsetTop + "px"; } } element.scrollTop = value | 0; prevTop = element.scrollTop; }; this.maxScrollTop = function() { return maxTop; }; this.maxScrollLeft = function() { return maxLeft; }; this.disable = function() { node = content.firstChild; while (node) { nextNode = node.nextSibling; element.appendChild(node); node = nextNode; } if (element === content.parentNode) { //in case disable() is called when it's already disabled. element.removeChild(content); } }; this.enable = function() { node = element.firstChild; if (node === content) { return; } while (node) { nextNode = node.nextSibling; content.appendChild(node); node = nextNode; } element.appendChild(content); this.calibrate(); }; this.calibrate = function(force) { var widthMatches = (element.clientWidth === elementWidth), x, y; prevTop = element.scrollTop; prevLeft = element.scrollLeft; if (widthMatches && element.clientHeight === elementHeight && content.offsetHeight === contentHeight && scrollWidth === element.scrollWidth && scrollHeight === element.scrollHeight && !force) { return; //no need to recalculate things if the width and height haven't changed. } if (offsetTop || offsetLeft) { x = this.left(); y = this.top(); this.left(-element.scrollLeft); this.top(-element.scrollTop); } //first, we need to remove any width constraints to see how the content naturally flows so that we can see if it's wider than the containing element. If so, we've got to record the amount of overage so that we can apply that as padding in order for browsers to correctly handle things. Then we switch back to a width of 100% (without that, some browsers don't flow the content correctly) if (!widthMatches || force) { style.display = "block"; style.width = "auto"; style.paddingRight = "0px"; extraPadRight = Math.max(0, element.scrollWidth - element.clientWidth); //if the content is wider than the container, we need to add the paddingLeft and paddingRight in order for things to behave correctly. if (extraPadRight) { extraPadRight += _getStyle(element, "paddingLeft") + (_addPaddingBR ? _getStyle(element, "paddingRight") : 0); } } style.display = "inline-block"; style.position = "relative"; style.overflow = "visible"; style.width = "100%"; style.paddingRight = extraPadRight + "px"; //some browsers neglect to factor in the bottom padding when calculating the scrollHeight, so we need to add that padding to the content when that happens. Allow a 2px margin for error if (_addPaddingBR) { style.paddingBottom = _getStyle(element, "paddingBottom", true); } if (_isOldIE) { style.zoom = "1"; } elementWidth = element.clientWidth; elementHeight = element.clientHeight; scrollWidth = element.scrollWidth; scrollHeight = element.scrollHeight; maxLeft = element.scrollWidth - elementWidth; maxTop = element.scrollHeight - elementHeight; contentHeight = content.offsetHeight; if (x || y) { this.left(x); this.top(y); } }; this.content = content; this.element = element; this._suspendTransforms = false; this.enable(); }, Draggable = function(target, vars) { EventDispatcher.call(this, target); target = _unwrapElement(target); //in case the target is a selector object or selector text if (!ThrowPropsPlugin) { ThrowPropsPlugin = (window.GreenSockGlobals || window).com.greensock.plugins.ThrowPropsPlugin; } this.vars = vars = vars || {}; this.target = target; this.x = this.y = this.rotation = 0; this.dragResistance = parseFloat(vars.dragResistance) || 0; this.edgeResistance = isNaN(vars.edgeResistance) ? 1 : parseFloat(vars.edgeResistance) || 0; this.lockAxis = vars.lockAxis; var type = (vars.type || (_isOldIE ? "top,left" : "x,y")).toLowerCase(), xyMode = (type.indexOf("x") !== -1 || type.indexOf("y") !== -1), rotationMode = (type.indexOf("rotation") !== -1), xProp = xyMode ? "x" : "left", yProp = xyMode ? "y" : "top", allowX = (type.indexOf("x") !== -1 || type.indexOf("left") !== -1 || type === "scroll"), allowY = (type.indexOf("y") !== -1 || type.indexOf("top") !== -1 || type === "scroll"), self = this, trigger = _unwrapElement(vars.trigger || vars.handle || target), killProps = {}, dragEndTime = 0, scrollProxy, startMouseX, startMouseY, startElementX, startElementY, hasBounds, hasDragCallback, maxX, minX, maxY, minY, tempVars, cssVars, touch, touchID, rotationOrigin, dirty, old, snapX, snapY, isClicking, touchEventTarget, lockedAxis, matrix, interrupted, //this method gets called on every tick of TweenLite.ticker which allows us to synchronize the renders to the core engine (which is typically synchronized with the display refresh via requestAnimationFrame). This is an optimization - it's better than applying the values inside the "mousemove" or "touchmove" event handler which may get called many times inbetween refreshes. render = function(suppressEvents) { if (dirty) { var x = self.x, y = self.y, min = 0.000001; if (x < min && x > -min) { //browsers don't handle super small decimals well. x = 0; } if (y < min && y > -min) { y = 0; } if (rotationMode) { cssVars.rotation = self.rotation = self.x; TweenLite.set(target, tempVars); } else { if (scrollProxy) { if (allowY) { scrollProxy.top(y); } if (allowX) { scrollProxy.left(x); } } else if (xyMode) { if (allowY) { cssVars.y = y; } if (allowX) { cssVars.x = x; } TweenLite.set(target, tempVars); } else { if (allowY) { target.style.top = y + "px"; } if (allowX) { target.style.left = x + "px"; } } } if (hasDragCallback && !suppressEvents) { _dispatchEvent(self, "drag", "onDrag"); } } dirty = false; }, //copies the x/y from the element (whether that be transforms, top/left, or ScrollProxy's top/left) to the Draggable's x and y (and rotation if necessary) properties so that they reflect reality and it also (optionally) applies any snapping necessary. This is used by the ThrowPropsPlugin tween in an onUpdate to ensure things are synced and snapped. syncXY = function(skipOnUpdate, skipSnap) { var snappedValue; if (xyMode) { if (!target._gsTransform) { //just in case the _gsTransform got wiped, like if the user called clearProps on the transform or something (very rare), doing an x tween forces a re-parsing of the transforms and population of the _gsTransform. TweenLite.set(target, {x:"+=0"}); } self.y = target._gsTransform.y; self.x = target._gsTransform.x; } else if (rotationMode) { if (!target._gsTransform) { //just in case the _gsTransform got wiped, like if the user called clearProps on the transform or something (very rare), doing an x tween forces a re-parsing of the transforms and population of the _gsTransform. TweenLite.set(target, {x:"+=0"}); } self.x = self.rotation = target._gsTransform.rotation; } else if (scrollProxy) { self.y = scrollProxy.top(); self.x = scrollProxy.left(); } else { self.y = parseInt(target.style.top, 10) || 0; self.x = parseInt(target.style.left, 10) || 0; } if ((snapX || snapY) && !skipSnap) { if (snapX) { snappedValue = snapX(self.x); if (snappedValue !== self.x) { self.x = snappedValue; if (rotationMode) { self.rotation = snappedValue; } dirty = true; } } if (snapY) { snappedValue = snapY(self.y); if (snappedValue !== self.y) { self.y = snappedValue; dirty = true; } } if (dirty) { render(true); } } if (vars.onThrowUpdate && !skipOnUpdate) { vars.onThrowUpdate.apply(vars.onThrowUpdateScope || self, vars.onThrowUpdateParams || _emptyArray); } }, calculateBounds = function() { var bounds, targetBounds, snap, snapIsRaw; hasBounds = false; if (scrollProxy) { scrollProxy.calibrate(); self.minX = minX = -scrollProxy.maxScrollLeft(); self.minY = minY = -scrollProxy.maxScrollTop(); self.maxX = maxX = self.maxY = maxY = 0; hasBounds = true; } else if (!!vars.bounds) { bounds = _getBounds(vars.bounds, target.parentNode); //could be a selector/jQuery object or a DOM element or a generic object like {top:0, left:100, width:1000, height:800} or {minX:100, maxX:1100, minY:0, maxY:800} if (rotationMode) { self.minX = minX = bounds.left; self.maxX = maxX = bounds.left + bounds.width; self.minY = minY = self.maxY = maxY = 0; } else if (vars.bounds.maxX !== undefined || vars.bounds.maxY !== undefined) { bounds = vars.bounds; self.minX = minX = bounds.minX; self.minY = minY = bounds.minY; self.maxX = maxX = bounds.maxX; self.maxY = maxY = bounds.maxY; } else { targetBounds = _getBounds(target, target.parentNode); self.minX = minX = _getStyle(target, xProp) + bounds.left - targetBounds.left; self.minY = minY = _getStyle(target, yProp) + bounds.top - targetBounds.top; self.maxX = maxX = minX + (bounds.width - targetBounds.width); self.maxY = maxY = minY + (bounds.height - targetBounds.height); } if (minX > maxX) { self.minX = maxX; self.maxX = maxX = minX; minX = self.minX; } if (minY > maxY) { self.minY = maxY; self.maxY = maxY = minY; minY = self.minY; } if (rotationMode) { self.minRotation = minX; self.maxRotation = maxX; } hasBounds = true; } if (vars.liveSnap) { snap = (vars.liveSnap === true) ? (vars.snap || {}) : vars.liveSnap; snapIsRaw = (snap instanceof Array || typeof(snap) === "function"); if (rotationMode) { snapX = buildSnapFunc((snapIsRaw ? snap : snap.rotation), minX, maxX, 1); snapY = null; } else { if (allowX) { snapX = buildSnapFunc((snapIsRaw ? snap : snap.x || snap.left || snap.scrollLeft), minX, maxX, scrollProxy ? -1 : 1); } if (allowY) { snapY = buildSnapFunc((snapIsRaw ? snap : snap.y || snap.top || snap.scrollTop), minY, maxY, scrollProxy ? -1 : 1); } } } }, animate = function(throwProps, forceZeroVelocity) { var snap, snapIsRaw, tween; if (throwProps && ThrowPropsPlugin) { if (throwProps === true) { snap = vars.snap || {}; snapIsRaw = (snap instanceof Array || typeof(snap) === "function"); throwProps = {resistance:(vars.throwResistance || vars.resistance || 1000) / (rotationMode ? 10 : 1)}; if (rotationMode) { throwProps.rotation = _parseThrowProps(self, snapIsRaw ? snap : snap.rotation, maxX, minX, 1, forceZeroVelocity); } else { if (allowX) { throwProps[xProp] = _parseThrowProps(self, snapIsRaw ? snap : snap.x || snap.left || snap.scrollLeft, maxX, minX, scrollProxy ? -1 : 1, forceZeroVelocity || (self.lockAxis && lockedAxis === "x")); } if (allowY) { throwProps[yProp] = _parseThrowProps(self, snapIsRaw ? snap : snap.y || snap.top || snap.scrollTop, maxY, minY, scrollProxy ? -1 : 1, forceZeroVelocity || (self.lockAxis && lockedAxis === "y")); } } } self.tween = tween = ThrowPropsPlugin.to(scrollProxy || target, {throwProps:throwProps, ease:(vars.ease || Power3.easeOut), onComplete:vars.onThrowComplete, onCompleteParams:vars.onThrowCompleteParams, onCompleteScope:(vars.onThrowCompleteScope || self), onUpdate:(vars.fastMode ? vars.onThrowUpdate : syncXY), onUpdateParams:(vars.fastMode ? vars.onThrowUpdateParams : null), onUpdateScope:(vars.onThrowUpdateScope || self)}, (isNaN(vars.maxDuration) ? 2 : vars.maxDuration), (isNaN(vars.minDuration) ? 0.5 : vars.minDuration), (isNaN(vars.overshootTolerance) ? (1 - self.edgeResistance) + 0.2 : vars.overshootTolerance)); if (!vars.fastMode) { //to populate the end values, we just scrub the tween to the end, record the values, and then jump back to the beginning. if (scrollProxy) { scrollProxy._suspendTransforms = true; //Microsoft browsers have a bug that causes them to briefly render the position incorrectly (it flashes to the end state when we seek() the tween even though we jump right back to the current position, and this only seems to happen when we're affecting both top and left), so we set a _suspendTransforms flag to prevent it from actually applying the values in the ScrollProxy. } tween.seek(tween.duration()); syncXY(true, true); self.endX = self.x; self.endY = self.y; if (rotationMode) { self.endRotation = self.x; } tween.play(0); syncXY(true, true); if (scrollProxy) { scrollProxy._suspendTransforms = false; } } } else if (hasBounds) { self.applyBounds(); } }, updateMatrix = function() { matrix = _getConcatenatedMatrix(target.parentNode, true); if (!matrix[1] && !matrix[2] && matrix[0] == 1 && matrix[3] == 1 && matrix[4] == 0 && matrix[5] == 0) { //if there are no transforms, we can optimize performance by not factoring in the matrix matrix = null; } }, recordStartPositions = function() { var edgeTolerance = 1 - self.edgeResistance; updateMatrix(); if (scrollProxy) { calculateBounds(); startElementY = scrollProxy.top(); startElementX = scrollProxy.left(); } else { //if the element is in the process of tweening, don't force snapping to occur because it could make it jump. Imagine the user throwing, then before it's done, clicking on the element in its inbetween state. if (isTweening()) { syncXY(true, true); calculateBounds(); } else { self.applyBounds(); } if (rotationMode) { rotationOrigin = _localToGlobal(target, {x:0, y:0}); syncXY(true, true); startElementX = self.x; //starting rotation (x always refers to rotation in type:"rotation", measured in degrees) startElementY = self.y = Math.atan2(rotationOrigin.y - startMouseY, startMouseX - rotationOrigin.x) * _RAD2DEG; } else { startElementY = _getStyle(target, yProp); //record the starting top and left values so that we can just add the mouse's movement to them later. startElementX = _getStyle(target, xProp); } } if (hasBounds && edgeTolerance) { if (startElementX > maxX) { startElementX = maxX + (startElementX - maxX) / edgeTolerance; } else if (startElementX < minX) { startElementX = minX - (minX - startElementX) / edgeTolerance; } if (!rotationMode) { if (startElementY > maxY) { startElementY = maxY + (startElementY - maxY) / edgeTolerance; } else if (startElementY < minY) { startElementY = minY - (minY - startElementY) / edgeTolerance; } } } }, isTweening = function() { return (self.tween && self.tween.isActive()); }, buildSnapFunc = function(snap, min, max, factor) { if (typeof(snap) === "function") { return function(n) { var edgeTolerance = !self.isPressed ? 1 : 1 - self.edgeResistance; //if we're tweening, disable the edgeTolerance because it's already factored into the tweening values (we don't want to apply it multiple times) return snap.call(self, (n > max ? max + (n - max) * edgeTolerance : (n < min) ? min + (n - min) * edgeTolerance : n)) * factor; }; } if (snap instanceof Array) { return function(n) { var i = snap.length, closest = 0, absDif = _max, val, dif; while (--i > -1) { val = snap[i]; dif = val - n; if (dif < 0) { dif = -dif; } if (dif < absDif && val >= min && val <= max) { closest = i; absDif = dif; } } return snap[closest]; }; } return isNaN(snap) ? function(n) { return n; } : function() { return snap * factor; }; }, //called when the mouse is pressed (or touch starts) onPress = function(e) { var temp; if (self.isPressed || !e) { //just in case the browser dispatches a "touchstart" and "mousedown" (some browsers emulate mouse events when using touches) return; } interrupted = isTweening(); self.pointerEvent = e; if (_touchEventLookup[e.type]) { //note: on iOS, BOTH touchmove and mousemove are dispatched, but the mousemove has pageY and pageX of 0 which would mess up the calculations and needlessly hurt performance. touchEventTarget = (e.type.indexOf("touch") !== -1) ? trigger : _doc; //pointer-based touches (for Microsoft browsers) don't remain locked to the original target like other browsers, so we must use the document instead. The event type would be "MSPointerDown" or "pointerdown". _addListener(touchEventTarget, "touchend", onRelease); _addListener(touchEventTarget, "touchmove", onMove); _addListener(touchEventTarget, "touchcancel", onRelease); _addListener(_doc, "touchstart", _onMultiTouchDocument); } else { touchEventTarget = null; _addListener(_doc, "mousemove", onMove); //attach these to the document instead of the box itself so that if the user's mouse moves too quickly (and off of the box), things still work. _addListener(_doc, "mouseup", onRelease); } isClicking = (_isClickable(e.target) && !vars.dragClickables); if (isClicking) { _addListener(e.target, "change", onRelease); //in some browsers, when you mousedown on a
element, no mouseup gets dispatched! So we listen for a "change" event instead. return; } if (_isOldIE) { e = _populateIEEvent(e, true); } else if (!(e.touches && e.touches.length > _dragCount + 1)) { //in some mobile browsers, e.preventDefault() when pressing on a link (or element with an onclick) will cause the link not to work. e.preventDefault(); if (e.preventManipulation) { e.preventManipulation(); //for some Microsoft browsers } } if (e.changedTouches) { //touch events store the data slightly differently e = touch = e.changedTouches[0]; touchID = e.identifier; } else if (e.pointerId) { touchID = e.pointerId; //for some Microsoft browsers } else { touch = null; } _dragCount++; _addToRenderQueue(render); //causes the Draggable to render on each "tick" of TweenLite.ticker (performance optimization - updating values in a mousemove can cause them to happen too frequently, like multiple times between frame redraws which is wasteful, and it also prevents values from updating properly in IE8) if (self.tween) { self.tween.kill(); } TweenLite.killTweensOf(scrollProxy || target, true, killProps); //in case the user tries to drag it before the last tween is done. if (scrollProxy) { TweenLite.killTweensOf(target, true, {scrollTo:1}); //just in case the original target's scroll position is being tweened somewhere else. } startMouseY = self.pointerY = e.pageY; //record the starting x and y so that we can calculate the movement from the original in _onMouseMove startMouseX = self.pointerX = e.pageX; recordStartPositions(); if (matrix) { temp = startMouseX * matrix[0] + startMouseY * matrix[2] + matrix[4]; startMouseY = startMouseX * matrix[1] + startMouseY * matrix[3] + matrix[5]; startMouseX = temp; } self.tween = lockedAxis = null; if (!rotationMode && !scrollProxy && vars.zIndexBoost !== false) { target.style.zIndex = Draggable.zIndex++; } self.isPressed = true; hasDragCallback = !!(vars.onDrag || self._listeners.drag); if (!rotationMode) { _setStyle(trigger, "cursor", vars.cursor || "move"); } _dispatchEvent(self, "press", "onPress"); }, //called every time the mouse/touch moves onMove = function(e) { if (_isMultiTouching || !self.isPressed) { return; } if (_isOldIE) { e = _populateIEEvent(e, true); } else { e.preventDefault(); if (e.preventManipulation) { //for some Microsoft browsers e.preventManipulation(); } } self.pointerEvent = e; var touches = e.changedTouches, dragTolerance = 1 - self.dragResistance, edgeTolerance = 1 - self.edgeResistance, xChange, yChange, x, y, i, dif, mouseX, mouseY, temp; if (touches) { //touch events store the data slightly differently e = touches[0]; if (e !== touch && e.identifier !== touchID) { //Usually changedTouches[0] will be what we're looking for, but in case it's not, look through the rest of the array...(and Android browsers don't reuse the event like iOS) i = touches.length; while (--i > -1 && (e = touches[i]).identifier !== touchID) {} if (i < 0) { return; } } } else if (e.pointerId && touchID && e.pointerId !== touchID) { //for some Microsoft browsers, we must attach the listener to the doc rather than the trigger so that when the finger moves outside the bounds of the trigger, things still work. So if the event we're receiving has a pointerId that doesn't match the touchID, ignore it (for multi-touch) return; } mouseX = self.pointerX = e.pageX; mouseY = self.pointerY = e.pageY; if (rotationMode) { y = Math.atan2(rotationOrigin.y - e.pageY, e.pageX - rotationOrigin.x) * _RAD2DEG; dif = self.y - y; self.y = y; if (dif > 180) { startElementY -= 360; } else if (dif < -180) { startElementY += 360; } x = startElementX + (startElementY - y) * dragTolerance; } else { if (matrix) { temp = mouseX * matrix[0] + mouseY * matrix[2] + matrix[4]; mouseY = mouseX * matrix[1] + mouseY * matrix[3] + matrix[5]; mouseX = temp; } yChange = (mouseY - startMouseY); xChange = (mouseX - startMouseX); if (yChange < 2 && yChange > -2) { yChange = 0; } if (xChange < 2 && xChange > -2) { xChange = 0; } if (self.lockAxis && (xChange || yChange)) { if (lockedAxis === "y" || (!lockedAxis && Math.abs(xChange) > Math.abs(yChange) && allowX)) { yChange = 0; lockedAxis = "y"; } else if (allowY) { xChange = 0; lockedAxis = "x"; } } x = startElementX + xChange * dragTolerance; y = startElementY + yChange * dragTolerance; } if (snapX || snapY) { if (snapX) { x = snapX(x); } if (snapY) { y = snapY(y); } } else if (hasBounds) { if (x > maxX) { x = maxX + (x - maxX) * edgeTolerance; } else if (x < minX) { x = minX + (x - minX) * edgeTolerance; } if (!rotationMode) { if (y > maxY) { y = maxY + (y - maxY) * edgeTolerance; } else if (y < minY) { y = minY + (y - minY) * edgeTolerance; } } } if (self.x !== x || (self.y !== y && !rotationMode)) { self.x = self.endX = x; if (rotationMode) { self.endRotation = x; } else { self.y = self.endY = y; } dirty = true; //a flag that indicates we need to render the target next time the TweenLite.ticker dispatches a "tick" event (typically on a requestAnimationFrame) - this is a performance optimization (we shouldn't render on every move because sometimes many move events can get dispatched between screen refreshes, and that'd be wasteful to render every time) if (!self.isDragging) { self.isDragging = true; _dispatchEvent(self, "dragstart", "onDragStart"); } } }, //called when the mouse/touch is released onRelease = function(e, force) { if (e && touchID && !force && e.pointerId && e.pointerId !== touchID) { //for some Microsoft browsers, we must attach the listener to the doc rather than the trigger so that when the finger moves outside the bounds of the trigger, things still work. So if the event we're receiving has a pointerId that doesn't match the touchID, ignore it (for multi-touch) return; } self.isPressed = false; var originalEvent = e, wasDragging = self.isDragging, touches, i; if (touchEventTarget) { _removeListener(touchEventTarget, "touchend", onRelease); _removeListener(touchEventTarget, "touchmove", onMove); _removeListener(touchEventTarget, "touchcancel", onRelease); _removeListener(_doc, "touchstart", _onMultiTouchDocument); } else { _removeListener(_doc, "mouseup", onRelease); _removeListener(_doc, "mousemove", onMove); } dirty = false; if (isClicking) { if (e) { _removeListener(e.target, "change", onRelease); } _dispatchEvent(self, "release", "onRelease"); _dispatchEvent(self, "click", "onClick"); isClicking = false; return; } _removeFromRenderQueue(render); if (!rotationMode) { _setStyle(trigger, "cursor", vars.cursor || "move"); } if (wasDragging) { dragEndTime = _lastDragTime = _getTime(); self.isDragging = false; } _dragCount--; if (e) { if (_isOldIE) { e = _populateIEEvent(e, false); } touches = e.changedTouches; if (touches) { //touch events store the data slightly differently e = touches[0]; if (e !== touch && e.identifier !== touchID) { //Usually changedTouches[0] will be what we're looking for, but in case it's not, look through the rest of the array...(and Android browsers don't reuse the event like iOS) i = touches.length; while (--i > -1 && (e = touches[i]).identifier !== touchID) {} if (i < 0) { return; } } } self.pointerEvent = originalEvent; self.pointerX = e.pageX; self.pointerY = e.pageY; } if (originalEvent && !wasDragging) { if (interrupted && vars.snap) { //otherwise, if the user clicks on the object while it's animating to a snapped position, and then releases without moving 3 pixels, it will just stay there (it should animate/snap) animate(vars.throwProps); } _dispatchEvent(self, "release", "onRelease"); _dispatchEvent(self, "click", "onClick"); } else { animate(vars.throwProps); //will skip if throwProps isn't defined or ThrowPropsPlugin isn't loaded. if (!_isOldIE && originalEvent && (vars.dragClickables || !_isClickable(originalEvent.target))) { originalEvent.preventDefault(); if (originalEvent.preventManipulation) { originalEvent.preventManipulation(); //for some Microsoft browsers } } _dispatchEvent(self, "release", "onRelease"); } if (wasDragging) { _dispatchEvent(self, "dragend", "onDragEnd"); } return true; }, onClick = function(e) { if (self.isPressed || _getTime() - dragEndTime < 20) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } if (e.preventManipulation) { e.preventManipulation(); //for some Microsoft browsers } } }; old = Draggable.get(this.target); if (old) { old.kill(); // avoids duplicates (an element can only be controlled by one Draggable) } //give the user access to start/stop dragging... this.startDrag = function(e) { onPress(e); if (!self.isDragging) { self.isDragging = true; _dispatchEvent(self, "dragstart", "onDragStart"); } }; this.drag = onMove; this.endDrag = function(e) { onRelease(e, true); }; this.timeSinceDrag = function() { return self.isDragging ? 0 : (_getTime() - dragEndTime) / 1000; }; this.hitTest = function(target, threshold) { return Draggable.hitTest(self.target, target, threshold); }; this.applyBounds = function(newBounds) { var x, y; if (newBounds && vars.bounds !== newBounds) { vars.bounds = newBounds; return self.update(true); } syncXY(true); calculateBounds(); if (hasBounds) { x = self.x; y = self.y; if (hasBounds) { if (x > maxX) { x = maxX; } else if (x < minX) { x = minX; } if (y > maxY) { y = maxY; } else if (y < minY) { y = minY; } } if (self.x !== x || self.y !== y) { self.x = self.endX = x; if (rotationMode) { self.endRotation = x; } else { self.y = self.endY = y; } dirty = true; render(); } } return self; }; this.update = function(applyBounds) { var x = self.x, y = self.y; updateMatrix(); if (applyBounds) { self.applyBounds(); } else { syncXY(true); } if (self.isPressed && (x !== self.x || (y !== self.y && !rotationMode))) { recordStartPositions(); } return self; }; this.enable = function() { var id; _addListener(trigger, "mousedown", onPress); _addListener(trigger, "touchstart", onPress); _addListener(trigger, "click", onClick); if (!rotationMode) { _setStyle(trigger, "cursor", vars.cursor || "move"); } trigger.ondragstart = trigger.onselectstart = _emptyFunc; //prevent text selection (and prevent IE from dragging images) _setStyle(trigger, "userSelect", "none"); _setStyle(trigger, "touchCallout", "none"); _setStyle(trigger, "touchAction", "none"); if (ThrowPropsPlugin) { ThrowPropsPlugin.track(scrollProxy || target, (xyMode ? "x,y" : rotationMode ? "rotation" : "top,left")); } if (scrollProxy) { scrollProxy.enable(); } target._gsDragID = id = "d" + (_lookupCount++); _lookup[id] = this; if (scrollProxy) { scrollProxy.element._gsDragID = id; } TweenLite.set(target, {x:"+=0"}); //simply ensures that there's a _gsTransform on the element. this.update(); return self; }; this.disable = function() { var dragging = this.isDragging; if (!rotationMode) { _setStyle(trigger, "cursor", null); } trigger.ondragstart = trigger.onselectstart = null; _setStyle(trigger, "userSelect", "text"); _setStyle(trigger, "touchCallout", "default"); _setStyle(trigger, "MSTouchAction", "auto"); _removeListener(trigger, "mousedown", onPress); _removeListener(trigger, "touchstart", onPress); _removeListener(trigger, "click", onClick); if (touchEventTarget) { _removeListener(touchEventTarget, "touchcancel", onRelease); _removeListener(touchEventTarget, "touchend", onRelease); _removeListener(touchEventTarget, "touchmove", onMove); } _removeListener(_doc, "mouseup", onRelease); _removeListener(_doc, "mousemove", onMove); if (ThrowPropsPlugin) { ThrowPropsPlugin.untrack(scrollProxy || target, (xyMode ? "x,y" : rotationMode ? "rotation" : "top,left")); } if (scrollProxy) { scrollProxy.disable(); } _removeFromRenderQueue(render); this.isDragging = this.isPressed = isClicking = false; if (dragging) { _dispatchEvent(this, "dragend", "onDragEnd"); } return self; }; this.kill = function() { TweenLite.killTweensOf(scrollProxy || target, true, killProps); self.disable(); delete _lookup[target._gsDragID]; return self; }; if (type.indexOf("scroll") !== -1) { scrollProxy = this.scrollProxy = new ScrollProxy(target, _extend({onKill:function() { //ScrollProxy's onKill() gets called if/when the ScrollProxy senses that the user interacted with the scroll position manually (like using the scrollbar). IE9 doesn't fire the "mouseup" properly when users drag the scrollbar of an element, so this works around that issue. if (self.isPressed) { onRelease(null); }}}, vars)); //a bug in many Android devices' stock browser causes scrollTop to get forced back to 0 after it is altered via JS, so we set overflow to "hidden" on mobile/touch devices (they hide the scroll bar anyway). That works around the bug. (This bug is discussed at https://code.google.com/p/android/issues/detail?id=19625) target.style.overflowY = (allowY && !_isTouchDevice) ? "auto" : "hidden"; target.style.overflowX = (allowX && !_isTouchDevice) ? "auto" : "hidden"; target = scrollProxy.content; } if (vars.force3D !== false) { TweenLite.set(target, {force3D:true}); //improve performance by forcing a GPU layer when possible } if (rotationMode) { killProps.rotation = 1; } else { if (allowX) { killProps[xProp] = 1; } if (allowY) { killProps[yProp] = 1; } } if (rotationMode) { tempVars = _tempVarsRotation; cssVars = tempVars.css; tempVars.overwrite = false; } else if (xyMode) { tempVars = (allowX && allowY) ? _tempVarsXY : allowX ? _tempVarsX : _tempVarsY; cssVars = tempVars.css; tempVars.overwrite = false; } this.enable(); }, p = Draggable.prototype = new EventDispatcher(); p.constructor = Draggable; p.pointerX = p.pointerY = 0; p.isDragging = p.isPressed = false; Draggable.version = "0.10.3"; Draggable.zIndex = 1000; _addListener(_doc, "touchcancel", function() { //some older Android devices intermittently stop dispatching "touchmove" events if we don't listen for "touchcancel" on the document. Very strange indeed. }); _addListener(_doc, "contextmenu", function(e) { var p; for (p in _lookup) { if (_lookup[p].isPressed) { _lookup[p].endDrag(); } } }); Draggable.create = function(targets, vars) { if (typeof(targets) === "string") { targets = TweenLite.selector(targets); } var a = _isArrayLike(targets) ? _flattenArray(targets) : [targets], i = a.length; while (--i > -1) { a[i] = new Draggable(a[i], vars); } return a; }; Draggable.get = function(target) { return _lookup[(_unwrapElement(target) || {})._gsDragID]; }; Draggable.timeSinceDrag = function() { return (_getTime() - _lastDragTime) / 1000; }; var _parseRect = function(e, undefined) { //accepts a DOM element, a mouse event, or a rectangle object and returns the corresponding rectangle with left, right, width, height, top, and bottom properties var r = (e.pageX !== undefined) ? {left:e.pageX, top:e.pageY, right:e.pageX + 1, bottom:e.pageY + 1} : (!e.nodeType && e.left !== undefined && e.top !== undefined) ? e : _unwrapElement(e).getBoundingClientRect(); if (r.right === undefined && r.width !== undefined) { r.right = r.left + r.width; r.bottom = r.top + r.height; } else if (!r.width) { //some browsers don't include width and height properties r.width = r.right - r.left; r.height = r.bottom - r.top; } return r; }; Draggable.hitTest = function(obj1, obj2, threshold) { // if (obj1 === obj2) { return false; } var r1 = _parseRect(obj1), r2 = _parseRect(obj2), isOutside = (r2.left > r1.right || r2.right < r1.left || r2.top > r1.bottom || r2.bottom < r1.top), overlap, area, isRatio; if (isOutside || !threshold) { return !isOutside; } isRatio = ((threshold + "").indexOf("%") !== -1); threshold = parseFloat(threshold) || 0; overlap = {left:Math.max(r1.left, r2.left), top:Math.max(r1.top, r2.top)}; overlap.width = Math.min(r1.right, r2.right) - overlap.left; overlap.height = Math.min(r1.bottom, r2.bottom) - overlap.top; if (overlap.width < 0 || overlap.height < 0) { return false; } if (isRatio) { threshold *= 0.01; area = overlap.width * overlap.height; return (area >= r1.width * r1.height * threshold || area >= r2.width * r2.height * threshold); } return (overlap.width > threshold && overlap.height > threshold); }; return Draggable; }, true); }); if (window._gsDefine) { window._gsQueue.pop()(); }