Commit d761bdc5 authored by Nature's avatar Nature

添加键盘滚动

parent 8b4d3638
;(function () { ;(function () {
'use strict'; 'use strict'
/** /**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
* *
* @codingstandard ftlabs-jsv2 * @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved] * @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt) * @license MIT License (see LICENSE.txt)
*/ */
/*jslint browser:true, node:true*/ /*jslint browser:true, node:true*/
/*global define, Event, Node*/
/*global define, Event, Node*/
/** /**
* Instantiate fast-clicking listeners on the specified layer. * Instantiate fast-clicking listeners on the specified layer.
* *
* @constructor * @constructor
* @param {Element} layer The layer to listen on * @param {Element} layer The layer to listen on
* @param {Object} [options={}] The options to override the defaults * @param {Object} [options={}] The options to override the defaults
*/ */
function FastClick(layer, options) { function FastClick (layer, options) {
var oldOnClick; var oldOnClick
options = options || {}; options = options || {}
/** /**
* Whether a click is currently being tracked. * Whether a click is currently being tracked.
* *
* @type boolean * @type boolean
*/ */
this.trackingClick = false; this.trackingClick = false
/**
/** * Timestamp for when click tracking started.
* Timestamp for when click tracking started. *
* * @type number
* @type number */
*/ this.trackingClickStart = 0
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
/** *
* The element being tracked for a click. * @type EventTarget
* */
* @type EventTarget this.targetElement = null
*/
this.targetElement = null; /**
* X-coordinate of touch start event.
*
/** * @type number
* X-coordinate of touch start event. */
* this.touchStartX = 0
* @type number
*/ /**
this.touchStartX = 0; * Y-coordinate of touch start event.
*
* @type number
/** */
* Y-coordinate of touch start event. this.touchStartY = 0
*
* @type number /**
*/ * ID of the last touch, retrieved from Touch.identifier.
this.touchStartY = 0; *
* @type number
*/
/** this.lastTouchIdentifier = 0
* ID of the last touch, retrieved from Touch.identifier.
* /**
* @type number * Touchmove boundary, beyond which a click will be cancelled.
*/ *
this.lastTouchIdentifier = 0; * @type number
*/
this.touchBoundary = options.touchBoundary || 10
/**
* Touchmove boundary, beyond which a click will be cancelled. /**
* * The FastClick layer.
* @type number *
*/ * @type Element
this.touchBoundary = options.touchBoundary || 10; */
this.layer = layer
/** /**
* The FastClick layer. * The minimum time between tap(touchstart and touchend) events
* *
* @type Element * @type number
*/ */
this.layer = layer; this.tapDelay = options.tapDelay || 200
/** /**
* The minimum time between tap(touchstart and touchend) events * The maximum time for a tap
* *
* @type number * @type number
*/ */
this.tapDelay = options.tapDelay || 200; this.tapTimeout = options.tapTimeout || 700
/** if (FastClick.notNeeded(layer)) {
* The maximum time for a tap return
* }
* @type number
*/ // Some old versions of Android don't have Function.prototype.bind
this.tapTimeout = options.tapTimeout || 700; function bind (method, context) {
return function () { return method.apply(context, arguments) }
if (FastClick.notNeeded(layer)) { }
return;
} var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']
var context = this
// Some old versions of Android don't have Function.prototype.bind for (var i = 0, l = methods.length; i < l; i++) {
function bind(method, context) { context[methods[i]] = bind(context[methods[i]], context)
return function() { return method.apply(context, arguments); }; }
}
// Set up event handlers as required
if (deviceIsAndroid) {
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']; layer.addEventListener('mouseover', this.onMouse, true)
var context = this; layer.addEventListener('mousedown', this.onMouse, true)
for (var i = 0, l = methods.length; i < l; i++) { layer.addEventListener('mouseup', this.onMouse, true)
context[methods[i]] = bind(context[methods[i]], context); }
}
layer.addEventListener('click', this.onClick, true)
// Set up event handlers as required layer.addEventListener('touchstart', this.onTouchStart, false)
if (deviceIsAndroid) { layer.addEventListener('touchmove', this.onTouchMove, false)
layer.addEventListener('mouseover', this.onMouse, true); layer.addEventListener('touchend', this.onTouchEnd, false)
layer.addEventListener('mousedown', this.onMouse, true); layer.addEventListener('touchcancel', this.onTouchCancel, false)
layer.addEventListener('mouseup', this.onMouse, true);
} // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
layer.addEventListener('click', this.onClick, true); // layer when they are cancelled.
layer.addEventListener('touchstart', this.onTouchStart, false); if (!Event.prototype.stopImmediatePropagation) {
layer.addEventListener('touchmove', this.onTouchMove, false); layer.removeEventListener = function (type, callback, capture) {
layer.addEventListener('touchend', this.onTouchEnd, false); var rmv = Node.prototype.removeEventListener
layer.addEventListener('touchcancel', this.onTouchCancel, false); if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture)
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) } else {
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick rmv.call(layer, type, callback, capture)
// layer when they are cancelled. }
if (!Event.prototype.stopImmediatePropagation) { }
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener; layer.addEventListener = function (type, callback, capture) {
if (type === 'click') { var adv = Node.prototype.addEventListener
rmv.call(layer, type, callback.hijacked || callback, capture); if (type === 'click') {
} else { adv.call(layer, type, callback.hijacked || (callback.hijacked = function (event) {
rmv.call(layer, type, callback, capture); if (!event.propagationStopped) {
} callback(event)
}; }
}), capture)
layer.addEventListener = function(type, callback, capture) { } else {
var adv = Node.prototype.addEventListener; adv.call(layer, type, callback, capture)
if (type === 'click') { }
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) { }
if (!event.propagationStopped) { }
callback(event);
} // If a handler is already declared in the element's onclick attribute, it will be fired before
}), capture); // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
} else { // adding it as listener.
adv.call(layer, type, callback, capture); if (typeof layer.onclick === 'function') {
}
}; // Android browser on at least 3.2 requires a new reference to the function in layer.onclick
} // - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick
// If a handler is already declared in the element's onclick attribute, it will be fired before layer.addEventListener('click', function (event) {
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and oldOnClick(event)
// adding it as listener. }, false)
if (typeof layer.onclick === 'function') { layer.onclick = null
}
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick }
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick; /**
layer.addEventListener('click', function(event) { * Windows Phone 8.1 fakes user agent string to look like Android and iPhone.
oldOnClick(event); *
}, false); * @type boolean
layer.onclick = null; */
} var deviceIsWindowsPhone = navigator.userAgent.indexOf('Windows Phone') >= 0
}
/**
/** * Android requires exceptions.
* Windows Phone 8.1 fakes user agent string to look like Android and iPhone. *
* * @type boolean
* @type boolean */
*/ var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone
var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;
/**
/** * iOS requires exceptions.
* Android requires exceptions. *
* * @type boolean
* @type boolean */
*/ var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;
/**
* iOS 4 requires an exception for select elements.
/** *
* iOS requires exceptions. * @type boolean
* */
* @type boolean var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent)
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone; /**
* iOS 6.0-7.* requires the target element to be manually derived
*
/** * @type boolean
* iOS 4 requires an exception for select elements. */
* var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent)
* @type boolean
*/ /**
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent); * BlackBerry requires exceptions.
*
* @type boolean
/** */
* iOS 6.0-7.* requires the target element to be manually derived var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0
*
* @type boolean
*/ var clickElement
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent); /**
* 当前滚动条的滚动高度
/** * @type {number}
* BlackBerry requires exceptions. */
* var scrollTop
* @type boolean
*/ /**
var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0; * 当前content的paddingBottom距离
*/
/** var contentPaddingBottom
* Determine whether a given element requires a native click.
* /**
* @param {EventTarget|Element} target Target DOM element * 是否滚动
* @returns {boolean} Returns true if the element needs a native click * @type {boolean}
*/ */
FastClick.prototype.needsClick = function(target) {
switch (target.nodeName.toLowerCase()) { var scollFlag = false
// Don't send a synthetic click to disabled inputs (issue #62) var innerHeight
case 'button': /**
case 'select': * Determine whether a given element requires a native click.
case 'textarea': *
if (target.disabled) { * @param {EventTarget|Element} target Target DOM element
return true; * @returns {boolean} Returns true if the element needs a native click
} */
FastClick.prototype.needsClick = function (target) {
break; switch (target.nodeName.toLowerCase()) {
case 'input':
// Don't send a synthetic click to disabled inputs (issue #62)
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68) case 'button':
if ((deviceIsIOS && target.type === 'file') || target.disabled) { case 'select':
return true; case 'textarea':
} if (target.disabled) {
return true
break; }
case 'label':
case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames break
case 'video': case 'input':
return true;
} // File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return (/\bneedsclick\b/).test(target.className); return true
}; }
break
/** case 'label':
* Determine whether a given element requires a call to focus to simulate click into element. case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames
* case 'video':
* @param {EventTarget|Element} target Target DOM element return true
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click. }
*/
FastClick.prototype.needsFocus = function(target) { return (/\bneedsclick\b/).test(target.className)
switch (target.nodeName.toLowerCase()) { }
case 'textarea':
return true; /**
case 'select': * Determine whether a given element requires a call to focus to simulate click into element.
return !deviceIsAndroid; *
case 'input': * @param {EventTarget|Element} target Target DOM element
switch (target.type) { * @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
case 'button': */
case 'checkbox': FastClick.prototype.needsFocus = function (target) {
case 'file': switch (target.nodeName.toLowerCase()) {
case 'image': case 'textarea':
case 'radio': return true
case 'submit': case 'select':
return false; return !deviceIsAndroid
} case 'input':
switch (target.type) {
// No point in attempting to focus disabled inputs case 'button':
return !target.disabled && !target.readOnly; case 'checkbox':
default: case 'file':
return (/\bneedsfocus\b/).test(target.className); case 'image':
} case 'radio':
}; case 'submit':
return false
}
/**
* Send a click event to the specified element. // No point in attempting to focus disabled inputs
* return !target.disabled && !target.readOnly
* @param {EventTarget|Element} targetElement default:
* @param {Event} event return (/\bneedsfocus\b/).test(target.className)
*/ }
FastClick.prototype.sendClick = function(targetElement, event) { }
var clickEvent, touch;
/**
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24) * Send a click event to the specified element.
if (document.activeElement && document.activeElement !== targetElement) { *
document.activeElement.blur(); * @param {EventTarget|Element} targetElement
} * @param {Event} event
*/
touch = event.changedTouches[0]; FastClick.prototype.sendClick = function (targetElement, event) {
var clickEvent, touch
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents'); // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); if (document.activeElement && document.activeElement !== targetElement) {
clickEvent.forwardedTouchEvent = true; document.activeElement.blur()
targetElement.dispatchEvent(clickEvent); }
};
touch = event.changedTouches[0]
FastClick.prototype.determineEventType = function(targetElement) {
// Synthesise a click event, with an extra attribute so it can be tracked
//Issue #159: Android Chrome Select Box does not open with a synthetic click event clickEvent = document.createEvent('MouseEvents')
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') { clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null)
return 'mousedown'; clickEvent.forwardedTouchEvent = true
} targetElement.dispatchEvent(clickEvent)
}
return 'click';
}; FastClick.prototype.determineEventType = function (targetElement) {
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
/** if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
* @param {EventTarget|Element} targetElement return 'mousedown'
*/ }
FastClick.prototype.focus = function(targetElement) {
var length; return 'click'
}
// Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
var disallowedTypes = ['time', 'month', 'email', 'number']; /**
if (deviceIsIOS && * @param {EventTarget|Element} targetElement
targetElement.setSelectionRange && */
targetElement.type.indexOf('date') !== 0 && FastClick.prototype.focus = function (targetElement) {
disallowedTypes.indexOf(targetElement.type) === -1) { var length
length = targetElement.value.length;
targetElement.focus(); // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
targetElement.setSelectionRange(length, length); var disallowedTypes = ['time', 'month', 'email', 'number']
} else { if (deviceIsIOS &&
targetElement.focus(); targetElement.setSelectionRange &&
} targetElement.type.indexOf('date') !== 0 &&
}; disallowedTypes.indexOf(targetElement.type) === -1) {
length = targetElement.value.length
targetElement.focus()
/** targetElement.setSelectionRange(length, length)
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it. } else {
* targetElement.focus()
* @param {EventTarget|Element} targetElement }
*/ }
FastClick.prototype.updateScrollParent = function(targetElement) {
var scrollParent, parentElement; /**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
scrollParent = targetElement.fastClickScrollParent; *
* @param {EventTarget|Element} targetElement
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the */
// target element was moved to another parent. FastClick.prototype.updateScrollParent = function (targetElement) {
if (!scrollParent || !scrollParent.contains(targetElement)) { var scrollParent, parentElement
parentElement = targetElement;
do { scrollParent = targetElement.fastClickScrollParent
if (parentElement.scrollHeight > parentElement.offsetHeight) { // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
scrollParent = parentElement; // target element was moved to another parent.
targetElement.fastClickScrollParent = parentElement; if (!scrollParent || !scrollParent.contains(targetElement)) {
break; parentElement = targetElement
} do {
// if (parentElement.scrollHeight > parentElement.offsetHeight) {
parentElement = parentElement.parentElement; if (parentElement.classList.contains('content')) {
} while (parentElement); scrollParent = parentElement
} targetElement.fastClickScrollParent = parentElement
targetElement.fastClickScrollParent.style.paddingBottom = '0px'
// Always update the scroll top tracker if possible. targetElement.fastClickScrollParent.style.transform = "translate(0px, 0px) scale(1) translateZ(0px)"
if (scrollParent) { break
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop; }
} parentElement = parentElement.parentElement
}; } while (parentElement)
}
// Always update the scroll top tracker if possible.
/**
* @param {EventTarget} targetElement if (scrollParent) {
* @returns {Element|EventTarget} scrollParent.fastClickLastScrollTop = scrollParent.scrollTop
*/ }
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) { }
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node. /**
if (eventTarget.nodeType === Node.TEXT_NODE) { * @param {EventTarget} targetElement
return eventTarget.parentNode; * @returns {Element|EventTarget}
} */
FastClick.prototype.getTargetElementFromEventTarget = function (eventTarget) {
return eventTarget;
}; // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode
/** }
* On touch start, record the position and scroll offset.
* return eventTarget
* @param {Event} event }
* @returns {boolean}
*/ /**
FastClick.prototype.onTouchStart = function(event) { * On touch start, record the position and scroll offset.
var targetElement, touch, selection; *
* @param {Event} event
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111). * @returns {boolean}
if (event.targetTouches.length > 1) { */
return true; FastClick.prototype.onTouchStart = function (event) {
} var targetElement, touch, selection
targetElement = this.getTargetElementFromEventTarget(event.target); // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
touch = event.targetTouches[0]; if (event.targetTouches.length > 1) {
return true
if (deviceIsIOS) { }
// Only trusted events will deselect text on iOS (issue #49) targetElement = this.getTargetElementFromEventTarget(event.target)
selection = window.getSelection(); touch = event.targetTouches[0]
if (selection.rangeCount && !selection.isCollapsed) {
return true; if (deviceIsIOS) {
}
// Only trusted events will deselect text on iOS (issue #49)
if (!deviceIsIOS4) { selection = window.getSelection()
if (selection.rangeCount && !selection.isCollapsed) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): return true
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched }
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an if (!deviceIsIOS4) {
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
// Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string, // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long, // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// random integers, it's safe to to continue if the identifier is 0 here. // with the same identifier as the touch event that previously triggered the click that triggered the alert.
if (touch.identifier && touch.identifier === this.lastTouchIdentifier) { // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
event.preventDefault(); // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
return false; // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string,
} // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long,
// random integers, it's safe to to continue if the identifier is 0 here.
this.lastTouchIdentifier = touch.identifier; if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {
event.preventDefault()
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: return false
// 1) the user does a fling scroll on the scrollable layer }
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger this.lastTouchIdentifier = touch.identifier
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42). // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
this.updateScrollParent(targetElement); // 1) the user does a fling scroll on the scrollable layer
} // 2) the user stops the fling scroll with another tap
} // then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
this.trackingClick = true; // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement; }
}
this.touchStartX = touch.pageX; this.updateScrollParent(targetElement)
this.touchStartY = touch.pageY; this.trackingClick = true
this.trackingClickStart = event.timeStamp
// Prevent phantom clicks on fast double-tap (issue #36) this.targetElement = targetElement
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault(); this.touchStartX = touch.pageX
} this.touchStartY = touch.pageY
return true; // Prevent phantom clicks on fast double-tap (issue #36)
}; if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault()
}
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started. return true
* }
* @param {Event} event
* @returns {boolean} /**
*/ * Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
FastClick.prototype.touchHasMoved = function(event) { *
var touch = event.changedTouches[0], boundary = this.touchBoundary; * @param {Event} event
* @returns {boolean}
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) { */
return true; FastClick.prototype.touchHasMoved = function (event) {
} var touch = event.changedTouches[0], boundary = this.touchBoundary
return false; if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
}; return true
}
/** return false
* Update the last position. }
*
* @param {Event} event /**
* @returns {boolean} * Update the last position.
*/ *
FastClick.prototype.onTouchMove = function(event) { * @param {Event} event
if (!this.trackingClick) { * @returns {boolean}
return true; */
} FastClick.prototype.onTouchMove = function (event) {
if (!this.trackingClick) {
// If the touch has moved, cancel the click tracking return true
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) { }
this.trackingClick = false;
this.targetElement = null; // If the touch has moved, cancel the click tracking
} if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false
return true; this.targetElement = null
}; }
return true
/** }
* Attempt to find the labelled control for the given label element.
* /**
* @param {EventTarget|HTMLLabelElement} labelElement * Attempt to find the labelled control for the given label element.
* @returns {Element|null} *
*/ * @param {EventTarget|HTMLLabelElement} labelElement
FastClick.prototype.findControl = function(labelElement) { * @returns {Element|null}
*/
// Fast path for newer browsers supporting the HTML5 control attribute FastClick.prototype.findControl = function (labelElement) {
if (labelElement.control !== undefined) {
return labelElement.control; // Fast path for newer browsers supporting the HTML5 control attribute
} if (labelElement.control !== undefined) {
return labelElement.control
// All browsers under test that support touch events also support the HTML5 htmlFor attribute }
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor); // All browsers under test that support touch events also support the HTML5 htmlFor attribute
} if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor)
// If no for attribute exists, attempt to retrieve the first labellable descendant element }
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea'); // If no for attribute exists, attempt to retrieve the first labellable descendant element
}; // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea')
}
/**
* On touch end, determine whether to send a click event at once. /**
* * On touch end, determine whether to send a click event at once.
* @param {Event} event *
* @returns {boolean} * @param {Event} event
*/ * @returns {boolean}
FastClick.prototype.onTouchEnd = function(event) { */
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement; FastClick.prototype.onTouchEnd = function (event) {
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement
if (!this.trackingClick) { if (!this.trackingClick) {
return true; return true
} }
// Prevent phantom clicks on fast double-tap (issue #36) // Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true; this.cancelNextClick = true
return true; return true
} }
if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) { if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {
return true; return true
} }
// Reset to prevent wrong click cancel on input (issue #156). // Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false; this.cancelNextClick = false
this.lastClickTime = event.timeStamp; this.lastClickTime = event.timeStamp
trackingClickStart = this.trackingClickStart; trackingClickStart = this.trackingClickStart
this.trackingClick = false; this.trackingClick = false
this.trackingClickStart = 0; this.trackingClickStart = 0
// On some iOS devices, the targetElement supplied with the event is invalid if the layer // On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that // is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked! // for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 . // See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) { if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0]; touch = event.changedTouches[0]
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement; targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent; targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent
} }
var pointY = touch = event.changedTouches[0].pageY;
targetTagName = targetElement.tagName.toLowerCase(); targetTagName = targetElement.tagName.toLowerCase()
if (targetTagName === 'label') { if (targetTagName === 'label') {
forElement = this.findControl(targetElement); forElement = this.findControl(targetElement)
if (forElement) { if (forElement) {
this.focus(targetElement); scollContent(pointY,targetElement)
if (deviceIsAndroid) { this.focus(targetElement)
return false; if (deviceIsAndroid) {
} return false
}
targetElement = forElement;
} targetElement = forElement
} else if (this.needsFocus(targetElement)) { }
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37). // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) { // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
this.targetElement = null; if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
return false; this.targetElement = null
} return false
}
this.focus(targetElement); scollContent(pointY,targetElement)
this.sendClick(targetElement, event); this.focus(targetElement)
this.sendClick(targetElement, event)
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others) // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
if (!deviceIsIOS || targetTagName !== 'select') { // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
this.targetElement = null; if (!deviceIsIOS || targetTagName !== 'select') {
event.preventDefault(); this.targetElement = null
} event.preventDefault()
}
return false;
} return false
}
if (deviceIsIOS && !deviceIsIOS4) {
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42). // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
scrollParent = targetElement.fastClickScrollParent; // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) { scrollParent = targetElement.fastClickScrollParent
return true; if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
} return true
} }
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted. // Prevent the actual click from going though - unless the target node is marked as requiring
if (!this.needsClick(targetElement)) { // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
event.preventDefault(); if (!this.needsClick(targetElement)) {
this.sendClick(targetElement, event); event.preventDefault()
} this.sendClick(targetElement, event)
}
return false;
}; return false
}
/** /**
* On touch cancel, stop tracking the click. * On touch cancel, stop tracking the click.
* *
* @returns {void} * @returns {void}
*/ */
FastClick.prototype.onTouchCancel = function() { FastClick.prototype.onTouchCancel = function () {
this.trackingClick = false; this.trackingClick = false
this.targetElement = null; this.targetElement = null
}; }
/**
/** * Determine mouse events which should be permitted.
* Determine mouse events which should be permitted. *
* * @param {Event} event
* @param {Event} event * @returns {boolean}
* @returns {boolean} */
*/ FastClick.prototype.onMouse = function (event) {
FastClick.prototype.onMouse = function(event) {
// If a target element was never set (because a touch event was never fired) allow the event
// If a target element was never set (because a touch event was never fired) allow the event if (!this.targetElement) {
if (!this.targetElement) { return true
return true; }
}
if (event.forwardedTouchEvent) {
if (event.forwardedTouchEvent) { return true
return true; }
}
// Programmatically generated events targeting a specific element should be permitted
// Programmatically generated events targeting a specific element should be permitted if (!event.cancelable) {
if (!event.cancelable) { return true
return true; }
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// Derive and check the target element to see whether the mouse event needs to be permitted; // unless explicitly enabled, prevent non-touch click events from triggering actions,
// unless explicitly enabled, prevent non-touch click events from triggering actions, // to prevent ghost/doubleclicks.
// to prevent ghost/doubleclicks. if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
// Prevent any user-added listeners declared on FastClick element from being fired. if (event.stopImmediatePropagation) {
if (event.stopImmediatePropagation) { event.stopImmediatePropagation()
event.stopImmediatePropagation(); } else {
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) event.propagationStopped = true
event.propagationStopped = true; }
}
// Cancel the event
// Cancel the event event.stopPropagation()
event.stopPropagation(); event.preventDefault()
event.preventDefault();
return false
return false; }
}
// If the mouse event is permitted, return true for the action to go through.
// If the mouse event is permitted, return true for the action to go through. return true
return true; }
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
/** * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* On actual clicks, determine whether this is a touch-generated click, a click action occurring * an actual click which should be permitted.
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or *
* an actual click which should be permitted. * @param {Event} event
* * @returns {boolean}
* @param {Event} event */
* @returns {boolean} FastClick.prototype.onClick = function (event) {
*/ var permitted
FastClick.prototype.onClick = function(event) {
var permitted; // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early. this.targetElement = null
if (this.trackingClick) { this.trackingClick = false
this.targetElement = null; return true
this.trackingClick = false; }
return true;
} // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target. return true
if (event.target.type === 'submit' && event.detail === 0) { }
return true;
} permitted = this.onMouse(event)
permitted = this.onMouse(event); // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through. this.targetElement = null
if (!permitted) { }
this.targetElement = null;
} // If clicks are permitted, return true for the action to go through.
return permitted
// If clicks are permitted, return true for the action to go through. }
return permitted;
}; /**
* Remove all FastClick's event listeners.
*
/** * @returns {void}
* Remove all FastClick's event listeners. */
* FastClick.prototype.destroy = function () {
* @returns {void} var layer = this.layer
*/
FastClick.prototype.destroy = function() { if (deviceIsAndroid) {
var layer = this.layer; layer.removeEventListener('mouseover', this.onMouse, true)
layer.removeEventListener('mousedown', this.onMouse, true)
if (deviceIsAndroid) { layer.removeEventListener('mouseup', this.onMouse, true)
layer.removeEventListener('mouseover', this.onMouse, true); }
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true); layer.removeEventListener('click', this.onClick, true)
} layer.removeEventListener('touchstart', this.onTouchStart, false)
layer.removeEventListener('touchmove', this.onTouchMove, false)
layer.removeEventListener('click', this.onClick, true); layer.removeEventListener('touchend', this.onTouchEnd, false)
layer.removeEventListener('touchstart', this.onTouchStart, false); layer.removeEventListener('touchcancel', this.onTouchCancel, false)
layer.removeEventListener('touchmove', this.onTouchMove, false); }
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false); /**
}; * Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
/** */
* Check whether FastClick is needed. FastClick.notNeeded = function (layer) {
* var metaViewport
* @param {Element} layer The layer to listen on var chromeVersion
*/ var blackberryVersion
FastClick.notNeeded = function(layer) { var firefoxVersion
var metaViewport;
var chromeVersion; // Devices that don't support touch don't need FastClick
var blackberryVersion; if (typeof window.ontouchstart === 'undefined') {
var firefoxVersion; return true
}
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') { // Chrome version - zero for other browsers
return true; chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1]
}
if (chromeVersion) {
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]')
if (chromeVersion) {
if (metaViewport) {
if (deviceIsAndroid) { // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true
if (metaViewport) { }
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89) // Chrome 32 and above with width=device-width or less don't need FastClick
if (metaViewport.content.indexOf('user-scalable=no') !== -1) { if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true; return true
} }
// Chrome 32 and above with width=device-width or less don't need FastClick }
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true; // Chrome desktop doesn't need FastClick (issue #15)
} } else {
} return true
}
// Chrome desktop doesn't need FastClick (issue #15) }
} else {
return true; if (deviceIsBlackBerry10) {
} blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/)
}
// BlackBerry 10.3+ does not require Fastclick library.
if (deviceIsBlackBerry10) { // https://github.com/ftlabs/fastclick/issues/251
blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/); if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {
metaViewport = document.querySelector('meta[name=viewport]')
// BlackBerry 10.3+ does not require Fastclick library.
// https://github.com/ftlabs/fastclick/issues/251 if (metaViewport) {
if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) { // user-scalable=no eliminates click delay.
metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true
if (metaViewport) { }
// user-scalable=no eliminates click delay. // width=device-width (or less than device-width) eliminates click delay.
if (metaViewport.content.indexOf('user-scalable=no') !== -1) { if (document.documentElement.scrollWidth <= window.outerWidth) {
return true; return true
} }
// width=device-width (or less than device-width) eliminates click delay. }
if (document.documentElement.scrollWidth <= window.outerWidth) { }
return true; }
}
} // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
} if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') {
} return true
}
// IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') { // Firefox version - zero for other browsers
return true; firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [, 0])[1]
}
if (firefoxVersion >= 27) {
// Firefox version - zero for other browsers // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896
firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
metaViewport = document.querySelector('meta[name=viewport]')
if (firefoxVersion >= 27) { if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896 return true
}
metaViewport = document.querySelector('meta[name=viewport]'); }
if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) {
return true; // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version
} // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
} if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {
return true
// IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version }
// http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx
if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') { return false
return true; }
}
window.addEventListener('native.keyboardhide', function (e) {
return false; if(scollFlag){
}; scollFlag=false
// clickElement.fastClickScrollParent.style.paddingBottom = contentPaddingBottom + 'px'
// clickElement.fastClickScrollParent.scrollTop =scrollTop
/** targetElement.fastClickScrollParent.style.paddingBottom = '0px'
* Factory method for creating a FastClick object /*clickElement.fastClickScrollParent.style.webkitTransform = "translate(0px, 0px) scale(1) translateZ(0px)"
* clickElement.fastClickScrollParent.style.MozTransform = "translate(0px, 0px) scale(1) translateZ(0px)"
* @param {Element} layer The layer to listen on clickElement.fastClickScrollParent.style.msTransform = "translate(0px, 0px) scale(1) translateZ(0px)"
* @param {Object} [options={}] The options to override the defaults clickElement.fastClickScrollParent.style.OTransform = "translate(0px, 0px) scale(1) translateZ(0px)"*/
*/ clickElement.fastClickScrollParent.style.transform = "translate(0px, 0px) scale(1) translateZ(0px)"
FastClick.attach = function(layer, options) { }
return new FastClick(layer, options); })
};
function scollContent (pointY,targetElement) {
innerHeight = window.innerHeight
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { var keyBoardHeight = getKeyBoardHeight()
clickElement = targetElement
// AMD. Register as an anonymous module. scrollTop = targetElement.fastClickScrollParent.scrollTop
define(function() { contentPaddingBottom = Number(targetElement.style.paddingBottom.replace('px', ''))
return FastClick; var scollHeight = (innerHeight - pointY) < keyBoardHeight ? (keyBoardHeight - (innerHeight - pointY)) : 0
}); if (scollHeight) {
} else if (typeof module !== 'undefined' && module.exports) { scollFlag = true
module.exports = FastClick.attach; targetElement.fastClickScrollParent.style.paddingBottom = (scollHeight+20) + 'px'
module.exports.FastClick = FastClick; // targetElement.fastClickScrollParent.scrollTop= (scrollTop + scollHeight)
} else { targetElement.fastClickScrollParent.style.transition = 'all .2s cubic-bezier(0.165, 0.84, 0.44, 1) 0s';
window.FastClick = FastClick;
} /*targetElement.fastClickScrollParent.style.webkitTransform = "translate(0px, -"+scollHeight+"px) scale(1) translateZ(0px)"
}()); targetElement.fastClickScrollParent.style.MozTransform = "translate(0px, -"+scollHeight+"px) scale(1) translateZ(0px)"
targetElement.fastClickScrollParent.style.msTransform = "translate(0px, -"+scollHeight+"px) scale(1) translateZ(0px)"
targetElement.fastClickScrollParent.style.OTransform = "translate(0px, -"+scollHeight+"px) scale(1) translateZ(0px)"*/
targetElement.fastClickScrollParent.style.transform = "translate(0px, -"+scollHeight+"px) scale(1) translateZ(0px)"
}
}
function getKeyBoardHeight () {
var innerWidth = window.innerWidth
if (deviceIsIOS) {
if (innerWidth >= 375 && innerHeight >= 812) {
return 400
}
return 370
} else {
return 275
}
}
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} [options={}] The options to override the defaults
*/
FastClick.attach = function (layer, options) {
return new FastClick(layer, options)
}
if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function () {
return FastClick
})
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach
module.exports.FastClick = FastClick
} else {
window.FastClick = FastClick
}
}())
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment