参考H5+的api文档
Barcode模块管理条码(一维码和二维码)扫描识别,支持常见的一维码(如EAN13码)及二维码(如QR码)。通过调用设备的摄像头对条码进行扫描识别,扫描到条码后进行解码并返回码数据内容及码类型。
Barcode模块可使得Web开发人员能快速方便调用设备的摄像头进行条码扫描识别,而不需要安装额外的扫描插件。规范建议条码识别引擎的支持规范定义的所有条码常量类型。

demo1:

如图效果展示:只实现了扫一扫功能

实现代码:

<template><div class="msgbox"><div class="header"><div class="head_goback"><van-icon name="cross" size="20"  @click="back" /></div><div class="title_head ellipsis"><span class="title_text">扫描二维码</span></div></div><div class="Detail"><div id="bcid"><div style="width:400px;height:400px; background-color: #000; margin: 15% auto 5%; text-align: center"></div></div><p style="text-align: center">将二维码放入框内,即可自动扫描</p><div style="text-align: center" class="sweep" @click="sweep">开始扫码</div></div>  </div>
</template>
<script>
var scan = null;//必须放全局export default {data() {return {}},mounted() {const self = thisif (window.plus) {self.plusReady()} else {document.addEventListener('plusready', self.plusReady, false)}document.addEventListener('DOMContentLoaded', function () {// alert('DOMLoaded')self.domready = trueself.plusReady()}, false)setTimeout(function () {self.sweep() // 扫码函数}, 1000)},watch:{},methods: {//   点击返回并关闭back: function() {const self = thisself.$router.push({name:'myIndex'})self.scan.close(); //关闭条码识别控件},plusReady() {const self = this// 获取窗口self.scan = new plus.barcode.Barcode('bcid')self.scan.onmarked = self.onmarked},// 开始扫码sweep () {const self = thisself.scan.start()},onmarked (type, result) {let t = thisswitch (type) {case plus.barcode.QR:type = 'QR'breakcase plus.barcode.EAN13:type = 'EAN13'breakcase plus.barcode.EAN8:type = 'EAN8'breakdefault:type = '其他' + typebreak}var result = result.replace(/\n/g, '')console.log(result) // 扫出来的值t.scan.close() //扫码成功后关闭扫码t.$router.push({// 跳转到对应的页面 name: '/processDetails',params: {urlid: result,}})}},}
</script>
<style scoped lang="less">.msgbox{background-color: #000;color: white;height: 100vh;overflow: hidden;.header{background-color: #000;height: 2.00533rem;width: 100%;text-align: center;line-height: 2.00533rem;display: flex;/*position: fixed;*/top:0;z-index: 99999;/deep/ .head_goback{padding-top: 10px;width: 10px;height: 10px;padding-left: 10px;}/deep/ .title_head{width: 92%;padding-top: 5px;text-align: center;color: white;font-size: 0.8533rem;letter-spacing: 2px;}}.Detail{width: 96%;margin: 0 auto;.session{.name{margin: 0.4rem 0;font-size: 0.4rem;color: #333333;font-weight: bold;}.useTutorials{background-color: #3998F7;border-radius: 5px;}.desc{margin: 0.4rem 0;font-size: 0.4rem;color: #333333;.title{font-weight: bold;}.intro{margin-top: 0.1rem;}}}p{font-size: 0.72rem;}.sweep{text-align: center;margin: 0.1rem auto;width:13.8667rem;height:1.7067rem;display: flex;justify-content: center;align-items: center;border-radius:1.024rem;font-size: 0.768rem;position: relative;z-index: 9999;color: white;background:#FF8C99;box-shadow:0px 6px 9px 0px rgba(255, 140, 153, 0.57);margin-top: 2rem;}}.start{text-align: center;margin: 0 auto;width:13.8667rem;height:1.7067rem;display: flex;justify-content: center;align-items: center;border-radius:1.024rem;font-size: 0.768rem;background:white;border: 2px solid rgba(255, 169, 163, 1);color: rgba(255, 169, 163, 1);margin-top: 0.64rem;}}
</style>

demo2:

如图效果展示:除了扫一扫功能,右上角可选择本地图片识别

实现代码:
引用的common.js在最低

<!DOCTYPE html>
<html><head><meta charset="utf-8"/><meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"/><meta name="HandheldFriendly" content="true"/><meta name="MobileOptimized" content="320"/><title>Hello H5+</title><script type="text/javascript" src="../js/common.js"></script><script type="text/javascript">
var ws=null,wo=null;
var scan=null;
// H5 plus事件处理
function plusReady(){// 获取窗口对象ws=plus.webview.currentWebview();wo=ws.opener();// 开始扫描ws.addEventListener('show', function(){scan=new plus.barcode.Barcode('bcid');scan.onmarked=onmarked;scan.start({conserve:true,filename:'_doc/barcode/'});createSubview();}, false);// 显示页面并关闭等待框ws.show('pop-in');
}
document.addEventListener('plusready', plusReady, false);// 二维码扫描成功
function onmarked(type, result, file){switch(type){case plus.barcode.QR:type = 'QR';break;case plus.barcode.EAN13:type = 'EAN13';break;case plus.barcode.EAN8:type = 'EAN8';break;default:type = '其它'+type;break;}result = result.replace(/\r\n/g, '');wo.evalJS("scaned('"+ type +"','"+ result +"','"+ file +"');");back();
}
// 创建子窗口
function createSubview(){//
}
// 从相册中选择二维码图片
function scanPicture(){plus.gallery.pick(function(path){plus.barcode.scan(path,onmarked,function(error){plus.nativeUI.alert('无法识别此图片');});}, function(err){console.log('Failed: '+err.message);});
}</script><link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/><style type="text/css">
#bcid {width: 100%;position: absolute;top: 0px;bottom: 0px;text-align: center;
}
.tip {color: #FFFFFF;font-weight: bold;text-shadow: 0px -1px #103E5C;
}</style></head><body style="background-color:#000000;"><div id="bcid"><div style="height:40%"></div><p class="tip">...载入中...</p></div></body>
</html>

demo3:

如图效果展示:除了扫一扫功能,右上角可开启闪光灯功能

实现代码:
引用的common.js在最低

<!DOCTYPE html>
<html><head><meta charset="utf-8"/><meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"/><meta name="HandheldFriendly" content="true"/><meta name="MobileOptimized" content="320"/><title>Hello H5+</title><script type="text/javascript" src="../js/common.js"></script><script type="text/javascript">
var ws=null,wo=null;
var scan=null;
// H5 plus事件处理
function plusReady(){// 获取窗口对象ws=plus.webview.currentWebview();nv=ws.getTitleNView();wo=ws.opener();// 开始扫描ws.addEventListener('show', function(){scan=new plus.barcode.Barcode('bcid',[plus.barcode.QR,plus.barcode.EAN8,plus.barcode.EAN13],{frameColor:'#00FF00',scanbarColor:'#00FF00'});scan.onmarked=onmarked;scan.start({conserve:true,filename:'_doc/barcode/'});createSubview();}, false);// 显示页面并关闭等待框ws.show('pop-in');
}
document.addEventListener('plusready', plusReady, false);// 二维码扫描成功
function onmarked(type, result, file){switch(type){case plus.barcode.QR:type = 'QR';break;case plus.barcode.EAN13:type = 'EAN13';break;case plus.barcode.EAN8:type = 'EAN8';break;default:type = '其它'+type;break;}result = result.replace(/\r\n/g, '');wo.evalJS("scaned('"+ type +"','"+ result +"','"+ file +"');");back();
}
// 创建子窗口
var view = null;
function createSubview(){view = new plus.nativeObj.View('nbutton', {bottom: '20px',left: '30%',width: '40%',height: '44px'}, [{tag: 'rect',id: 'rect',rectStyles: {radius: '8px',color: 'rgba(255,0,0,0.8)'}},{tag: 'font',id: 'text',text: '暂 停',textStyles: {color: '#FFFFFF'}}]);// 处理事件view.addEventListener('click', function(e){switchScan();}, false);view.addEventListener('touchstart', function(e){view.drawRect({radius: '8px',color: 'rgba(255,0,0,0.5)'}, {}, 'rect');}, false);view.addEventListener('touchend', function(e){view.drawRect({radius: '8px',color: 'rgba(255,0,0,0.8)'}, {}, 'rect');}, false);ws.append(view);
}
// 开关闪光灯
var bFlash = false;
var AVCaptureDevice=null;
var Camera=null;
function switchFlash(){bFlash = !bFlash;scan.setFlash(bFlash);ws.setStyle({titleNView: {buttons: [{fontSrc: '_www/helloh5.ttf',text: (bFlash?'\ue400':'\ue401'),fontSize: '18px',onclick: 'javascript:switchFlash()'}]}});
}
// 切换扫描
var bScan = false;
function switchScan(){if(bScan){scan.start({conserve:true, filename:'_doc/barcode/'});view&&(view.drawText('暂 停', {}, {color:'#FFFFFF'}, 'text'));}else{scan.cancel();view&&(view.drawText('开 始', {}, {color:'#FFFFFF'}, 'text'));}bScan=!bScan;
}</script><link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/><style type="text/css">
#bcid {width: 100%;position: absolute;top: 0px;bottom: 0px;text-align: center;
}
.tip {color: #FFFFFF;font-weight: bold;text-shadow: 0px -1px #103E5C;
}</style></head><body style="background-color:#000000;"><div id="bcid"><div style="height:40%"></div><p class="tip">...载入中...</p></div></body>
</html>

commin.js里内容

(function(w){
// 空函数
function shield(){return false;
}
document.addEventListener('touchstart', shield, false);//取消浏览器的所有事件,使得active的样式在手机上正常生效
document.oncontextmenu=shield;//屏蔽选择函数
// H5 plus事件处理
var ws=null,as='pop-in';
function plusReady(){ws=plus.webview.currentWebview();plus.key.addEventListener('backbutton', function(){back();},false);
}
if(w.plus){plusReady();
}else{document.addEventListener('plusready', plusReady, false);
}
// DOMContentLoaded事件处理
document.addEventListener('DOMContentLoaded', function(){gInit();document.body.onselectstart=shield;
},false);
// 返回
w.back=function(hide){if(w.plus){ws||(ws=plus.webview.currentWebview());(hide||ws.preate)?ws.hide('auto'):ws.close('auto');}else if(history.length>1){history.back();}else{w.close();}
};
// 处理点击事件
var openw=null;
/*** 打开新窗口* @param {URIString} id : 要打开页面url* @param {String} t : 页面标题名称* @param {JSON} ws : Webview窗口属性*/
w.clicked=function(id, t, ws){if(openw){//避免多次打开同一个页面return null;}if(w.plus){ws=ws||{};ws.scrollIndicator||(ws.scrollIndicator='none');ws.scalable||(ws.scalable=false);ws.backButtonAutoControl||(ws.backButtonAutoControl='close');ws.titleNView=ws.titleNView||{autoBackButton:true};ws.titleNView.backgroundColor = '#D74B28';ws.titleNView.titleColor = '#CCCCCC';ws.doc&&(ws.titleNView.buttons=ws.titleNView.buttons||[],ws.titleNView.buttons.push({fontSrc:'_www/helloh5.ttf',text:'\ue301',fontSize:'20px',onclick:'javascript:openDoc()'}));t&&(ws.titleNView.titleText=t);openw = plus.webview.create(id, id, ws);openw.addEventListener('loaded', function(){openw.show(as);}, false);openw.addEventListener('close', function(){openw=null;}, false);return openw;}else{w.open(id);}return null;
};
/*** 创建新窗口(无原始标题栏),* @param {URIString} id : 要打开页面url* @param {JSON} ws : Webview窗口属性*/
w.createWithoutTitle=function(id, ws){if(openw){//避免多次打开同一个页面return null;}if(w.plus){ws=ws||{};ws.scrollIndicator||(ws.scrollIndicator='none');ws.scalable||(ws.scalable=false);ws.backButtonAutoControl||(ws.backButtonAutoControl='close');openw = plus.webview.create(id, id, ws);openw.addEventListener('close', function(){openw=null;}, false);return openw;}else{w.open(id);}return null;
};
/*** 打开文档页面* @param {URIString} c : 要打开页面url*/
w.openDoc=function(c){plus.webview.create(c, 'document', {titleNView:{autoBackButton:true,backgroundColor:'#D74B28',titleColor:'#CCCCCC'},backButtonAutoControl:'close',scalable:false}).show('pop-in');
};
/*** 兼容提示*/
w.compatibleConfirm=function(){plus.nativeUI.confirm('本OS原生层面不提供该控件,需使用mui框架实现类似效果。请点击“确定”下载Hello mui示例',function(e){if(0==e.index){plus.runtime.openURL("http://www.dcloud.io/hellomui/");}},"",["确定","取消"]);
}
// 通用元素对象
var _dout_=null;
w.gInit=function(){_dout_=document.getElementById("output");
};
// 清空输出内容
w.outClean=function(){_dout_.innerText="";_dout_.scrollTop=0;//在iOS8存在不滚动的现象
};
// 输出内容
w.outSet=function(s){console.log(s);_dout_.innerText=s+"\n";(0==_dout_.scrollTop)&&(_dout_.scrollTop=1);//在iOS8存在不滚动的现象
};
// 输出行内容
w.outLine=function(s){console.log(s);_dout_.innerText+=s+"\n";(0==_dout_.scrollTop)&&(_dout_.scrollTop=1);//在iOS8存在不滚动的现象
};
// 格式化时长字符串,格式为"HH:MM:SS"
w.timeToStr=function(ts){if(isNaN(ts)){return "--:--:--";}var h=parseInt(ts/3600);var m=parseInt((ts%3600)/60);var s=parseInt(ts%60);return (ultZeroize(h)+":"+ultZeroize(m)+":"+ultZeroize(s));
};
// 格式化日期时间字符串,格式为"YYYY-MM-DD HH:MM:SS"
w.dateToStr=function(d){return (d.getFullYear()+"-"+ultZeroize(d.getMonth()+1)+"-"+ultZeroize(d.getDate())+" "+ultZeroize(d.getHours())+":"+ultZeroize(d.getMinutes())+":"+ultZeroize(d.getSeconds()));
};
/*** zeroize value with length(default is 2).* @param {Object} v* @param {Number} l* @return {String} */
w.ultZeroize=function(v,l){var z="";l=l||2;v=String(v);for(var i=0;i<l-v.length;i++){z+="0";}return z+v;
};
})(window);// fast click
;(function () {'use strict';/*** @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.** @codingstandard ftlabs-jsv2* @copyright The Financial Times Limited [All Rights Reserved]* @license MIT License (see LICENSE.txt)*//*jslint browser:true, node:true*//*global define, Event, Node*//*** Instantiate fast-clicking listeners on the specified layer.** @constructor* @param {Element} layer The layer to listen on* @param {Object} [options={}] The options to override the defaults*/function FastClick(layer, options) {var oldOnClick;options = options || {};/*** Whether a click is currently being tracked.** @type boolean*/this.trackingClick = false;/*** Timestamp for when click tracking started.** @type number*/this.trackingClickStart = 0;/*** The element being tracked for a click.** @type EventTarget*/this.targetElement = null;/*** X-coordinate of touch start event.** @type number*/this.touchStartX = 0;/*** Y-coordinate of touch start event.** @type number*/this.touchStartY = 0;/*** ID of the last touch, retrieved from Touch.identifier.** @type number*/this.lastTouchIdentifier = 0;/*** Touchmove boundary, beyond which a click will be cancelled.** @type number*/this.touchBoundary = options.touchBoundary || 10;/*** The FastClick layer.** @type Element*/this.layer = layer;/*** The minimum time between tap(touchstart and touchend) events** @type number*/this.tapDelay = options.tapDelay || 200;/*** The maximum time for a tap** @type number*/this.tapTimeout = options.tapTimeout || 700;if (FastClick.notNeeded(layer)) {return;}// Some old versions of Android don't have Function.prototype.bindfunction bind(method, context) {return function() { return method.apply(context, arguments); };}var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];var context = this;for (var i = 0, l = methods.length; i < l; i++) {context[methods[i]] = bind(context[methods[i]], context);}// Set up event handlers as requiredif (deviceIsAndroid) {layer.addEventListener('mouseover', this.onMouse, true);layer.addEventListener('mousedown', this.onMouse, true);layer.addEventListener('mouseup', this.onMouse, true);}layer.addEventListener('click', this.onClick, true);layer.addEventListener('touchstart', this.onTouchStart, false);layer.addEventListener('touchmove', this.onTouchMove, false);layer.addEventListener('touchend', this.onTouchEnd, false);layer.addEventListener('touchcancel', this.onTouchCancel, false);// 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 when they are cancelled.if (!Event.prototype.stopImmediatePropagation) {layer.removeEventListener = function(type, callback, capture) {var rmv = Node.prototype.removeEventListener;if (type === 'click') {rmv.call(layer, type, callback.hijacked || callback, capture);} else {rmv.call(layer, type, callback, capture);}};layer.addEventListener = function(type, callback, capture) {var adv = Node.prototype.addEventListener;if (type === 'click') {adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {if (!event.propagationStopped) {callback(event);}}), capture);} else {adv.call(layer, type, callback, capture);}};}// If a handler is already declared in the element's onclick attribute, it will be fired before// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and// adding it as listener.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;layer.addEventListener('click', function(event) {oldOnClick(event);}, false);layer.onclick = null;}}/*** Windows Phone 8.1 fakes user agent string to look like Android and iPhone.** @type boolean*/var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0;/*** Android requires exceptions.** @type boolean*/var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone;/*** iOS requires exceptions.** @type boolean*/var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone;/*** iOS 4 requires an exception for select elements.** @type boolean*/var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);/*** iOS 6.0-7.* requires the target element to be manually derived** @type boolean*/var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent);/*** BlackBerry requires exceptions.** @type boolean*/var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0;/*** 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*/FastClick.prototype.needsClick = function(target) {switch (target.nodeName.toLowerCase()) {// Don't send a synthetic click to disabled inputs (issue #62)case 'button':case 'select':case 'textarea':if (target.disabled) {return true;}break;case 'input':// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)if ((deviceIsIOS && target.type === 'file') || target.disabled) {return true;}break;case 'label':case 'iframe': // iOS8 homescreen apps can prevent events bubbling into framescase 'video':return true;}return (/\bneedsclick\b/).test(target.className);};/*** Determine whether a given element requires a call to focus to simulate click into element.** @param {EventTarget|Element} target Target DOM element* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.*/FastClick.prototype.needsFocus = function(target) {switch (target.nodeName.toLowerCase()) {case 'textarea':return true;case 'select':return !deviceIsAndroid;case 'input':switch (target.type) {case 'button':case 'checkbox':case 'file':case 'image':case 'radio':case 'submit':return false;}// No point in attempting to focus disabled inputsreturn !target.disabled && !target.readOnly;default:return (/\bneedsfocus\b/).test(target.className);}};/*** Send a click event to the specified element.** @param {EventTarget|Element} targetElement* @param {Event} event*/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)if (document.activeElement && document.activeElement !== targetElement) {document.activeElement.blur();}touch = event.changedTouches[0];// Synthesise a click event, with an extra attribute so it can be trackedclickEvent = document.createEvent('MouseEvents');clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);clickEvent.forwardedTouchEvent = true;targetElement.dispatchEvent(clickEvent);};FastClick.prototype.determineEventType = function(targetElement) {//Issue #159: Android Chrome Select Box does not open with a synthetic click eventif (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {return 'mousedown';}return 'click';};/*** @param {EventTarget|Element} targetElement*/FastClick.prototype.focus = function(targetElement) {var length;// 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.if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') {length = targetElement.value.length;targetElement.setSelectionRange(length, length);} else {targetElement.focus();}};/*** Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.** @param {EventTarget|Element} targetElement*/FastClick.prototype.updateScrollParent = function(targetElement) {var scrollParent, parentElement;scrollParent = targetElement.fastClickScrollParent;// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the// target element was moved to another parent.if (!scrollParent || !scrollParent.contains(targetElement)) {parentElement = targetElement;do {if (parentElement.scrollHeight > parentElement.offsetHeight) {scrollParent = parentElement;targetElement.fastClickScrollParent = parentElement;break;}parentElement = parentElement.parentElement;} while (parentElement);}// Always update the scroll top tracker if possible.if (scrollParent) {scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;}};/*** @param {EventTarget} targetElement* @returns {Element|EventTarget}*/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) {return eventTarget.parentNode;}return eventTarget;};/*** On touch start, record the position and scroll offset.** @param {Event} event* @returns {boolean}*/FastClick.prototype.onTouchStart = function(event) {var targetElement, touch, selection;// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).if (event.targetTouches.length > 1) {return true;}targetElement = this.getTargetElementFromEventTarget(event.target);touch = event.targetTouches[0];if (deviceIsIOS) {// Only trusted events will deselect text on iOS (issue #49)selection = window.getSelection();if (selection.rangeCount && !selection.isCollapsed) {return true;}if (!deviceIsIOS4) {// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):// 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// 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,// 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.if (touch.identifier && touch.identifier === this.lastTouchIdentifier) {event.preventDefault();return false;}this.lastTouchIdentifier = touch.identifier;// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:// 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// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).this.updateScrollParent(targetElement);}}this.trackingClick = true;this.trackingClickStart = event.timeStamp;this.targetElement = targetElement;this.touchStartX = touch.pageX;this.touchStartY = touch.pageY;// Prevent phantom clicks on fast double-tap (issue #36)if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {event.preventDefault();}return true;};/*** Based on a touchmove event object, check whether the touch has moved past a boundary since it started.** @param {Event} event* @returns {boolean}*/FastClick.prototype.touchHasMoved = function(event) {var touch = event.changedTouches[0], boundary = this.touchBoundary;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}*/FastClick.prototype.onTouchMove = function(event) {if (!this.trackingClick) {return true;}// If the touch has moved, cancel the click trackingif (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {this.trackingClick = false;this.targetElement = null;}return true;};/*** Attempt to find the labelled control for the given label element.** @param {EventTarget|HTMLLabelElement} labelElement* @returns {Element|null}*/FastClick.prototype.findControl = function(labelElement) {// Fast path for newer browsers supporting the HTML5 control attributeif (labelElement.control !== undefined) {return labelElement.control;}// All browsers under test that support touch events also support the HTML5 htmlFor attributeif (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-labelreturn 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.** @param {Event} event* @returns {boolean}*/FastClick.prototype.onTouchEnd = function(event) {var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;if (!this.trackingClick) {return true;}// Prevent phantom clicks on fast double-tap (issue #36)if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {this.cancelNextClick = true;return true;}if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) {return true;}// Reset to prevent wrong click cancel on input (issue #156).this.cancelNextClick = false;this.lastClickTime = event.timeStamp;trackingClickStart = this.trackingClickStart;this.trackingClick = false;this.trackingClickStart = 0;// 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// for this to function correctly, it must be called *after* the event target is checked!// See issue #57; also filed as rdar://13048589 .if (deviceIsIOSWithBadTarget) {touch = event.changedTouches[0];// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to nulltargetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;}targetTagName = targetElement.tagName.toLowerCase();if (targetTagName === 'label') {forElement = this.findControl(targetElement);if (forElement) {this.focus(targetElement);if (deviceIsAndroid) {return false;}targetElement = forElement;}} 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).if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {this.targetElement = null;return false;}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)if (!deviceIsIOS || targetTagName !== 'select') {this.targetElement = null;event.preventDefault();}return false;}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).scrollParent = targetElement.fastClickScrollParent;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.if (!this.needsClick(targetElement)) {event.preventDefault();this.sendClick(targetElement, event);}return false;};/*** On touch cancel, stop tracking the click.** @returns {void}*/FastClick.prototype.onTouchCancel = function() {this.trackingClick = false;this.targetElement = null;};/*** Determine mouse events which should be permitted.** @param {Event} event* @returns {boolean}*/FastClick.prototype.onMouse = function(event) {// If a target element was never set (because a touch event was never fired) allow the eventif (!this.targetElement) {return true;}if (event.forwardedTouchEvent) {return true;}// Programmatically generated events targeting a specific element should be permittedif (!event.cancelable) {return true;}// 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,// to prevent ghost/doubleclicks.if (!this.needsClick(this.targetElement) || this.cancelNextClick) {// Prevent any user-added listeners declared on FastClick element from being fired.if (event.stopImmediatePropagation) {event.stopImmediatePropagation();} else {// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)event.propagationStopped = true;}// Cancel the eventevent.stopPropagation();event.preventDefault();return false;}// If the mouse event is permitted, return true for the action to go through.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* an actual click which should be permitted.** @param {Event} event* @returns {boolean}*/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) {this.targetElement = null;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) {return true;}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) {this.targetElement = null;}// If clicks are permitted, return true for the action to go through.return permitted;};/*** Remove all FastClick's event listeners.** @returns {void}*/FastClick.prototype.destroy = function() {var layer = this.layer;if (deviceIsAndroid) {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('touchend', this.onTouchEnd, false);layer.removeEventListener('touchcancel', this.onTouchCancel, false);};/*** Check whether FastClick is needed.** @param {Element} layer The layer to listen on*/FastClick.notNeeded = function(layer) {var metaViewport;var chromeVersion;var blackberryVersion;var firefoxVersion;// Devices that don't support touch don't need FastClickif (typeof window.ontouchstart === 'undefined') {return true;}// Chrome version - zero for other browserschromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];if (chromeVersion) {if (deviceIsAndroid) {metaViewport = document.querySelector('meta[name=viewport]');if (metaViewport) {// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)if (metaViewport.content.indexOf('user-scalable=no') !== -1) {return true;}// Chrome 32 and above with width=device-width or less don't need FastClickif (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {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.// https://github.com/ftlabs/fastclick/issues/251if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) {metaViewport = document.querySelector('meta[name=viewport]');if (metaViewport) {// user-scalable=no eliminates click delay.if (metaViewport.content.indexOf('user-scalable=no') !== -1) {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;}// Firefox version - zero for other browsersfirefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];if (firefoxVersion >= 27) {// Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896metaViewport = 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.aspxif (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') {return true;}return false;};/*** 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;}document.addEventListener('DOMContentLoaded', function() {FastClick.attach(document.body);
}, false);}());

注:转载请标明出处

H5+ 调用Barcode 实现二维码扫一扫相关推荐

  1. 移动端开发vue使用Barcode实现二维码、条形码扫码

    实现效果 0 HTML <template><div class="content"><header><section class=&qu ...

  2. js调用微信利用二维码扫码登录

    js调用微信利用二维码扫码登录 准备工作 网站应用微信登录是基于OAuth2.0协议标准构建的微信OAuth2.0授权登录系统. 在进行微信OAuth2.0授权登录接入之前,在微信开放平台注册开发者帐 ...

  3. H5移动版识别二维码和条形码

    H5移动版识别二维码和条形码(PC和移动端都兼容) 一.需要引入JS文件 <script src="https://www.jq22.com/jquery/jquery-1.10.2. ...

  4. PC端调用摄像头扫描二维码,拿到二维码信息

    PC端调用摄像头扫描二维码,拿到二维码信息 <template><el-dialogtitle="扫描设备二维码":visible.sync="dial ...

  5. C# 调用摄像头解析二维码

    上次的二维码项目中,在解析的时候用的是扫码枪自动解析并以键盘形式输出,二次开发及通用性不高.本次项目使用AForge库调用摄像头采集二维码照片,再使用ZXing库解析二维码,较之前通用性更高. 一.调 ...

  6. 调用网易云二维码登录API,实现微信小程序登录

    调用网易云二维码登录API,实现微信小程序登录 首先前往网易云音乐API官网 binaryify.github.io/NeteaseClou- 首先根据文档的链接下载好配置文件,再根据官方文档启动好本 ...

  7. wechat-0050,微信公众号,带参数的二维码获取与扫码事件推送

    demo:https://github.com/wenrongyao/wechat-demo 摘要:这篇帖子讲述如何获取带参数的二维码,以及扫码带参数的二维码后的事件接收. 微信开发者文档:https ...

  8. 怎么把视频生成二维码?微信扫二维码就可以观看?不要广告的

    发布时间:2019-7-30 原创内容:阿酷 怎么把视频生成二维码?微信扫二维码就可以观看?不要广告的 如今,二维码的应用越来越广了,也非常方便,那么如何把视频转换生成二维码呢?网页地址转换二维码的工 ...

  9. 微信生成带参数的二维码,合成海报,扫码后推送小程序?

    微信服务号渠道二维码功能,支持生成带参数二维码,合成海报二维码,微信扫码后推送内容:结合微号帮平台48小时信息推送,推送微信小程序. 带参二维码 海报二维码 微信扫码后回复 48小时信息推送 在微号帮 ...

最新文章

  1. iOS之一个iOS开发人员完整的学习路线
  2. oracle导出脚本文件怎么打开,Windows下的Oracle导出脚本 -电脑资料
  3. 关于MySQL的SLEEP(N)函数
  4. WINDOWS消息系统简洁图解
  5. 读《世界是数字的》有感
  6. android 图像对比,Android中比较两个图片是否一致的问题
  7. Android之jni编译出现no matching function for call to ‘_JNIEnv::GetJava(JNIEnv* , Java VM**)‘解决办法)‘
  8. Math、Date内置对象方法整理
  9. 程序逻辑上多一些提示
  10. 微软学术搜索项目 10个版本的历程
  11. 用Java实现一个简单的链表迭代器
  12. linux重启后版本变了,linux – 重启后如何使设备映射保持不变?
  13. oracle禁用ctss,CTSS服务介绍及模式调整
  14. fps up up!!!
  15. GridView选中,编辑,取消,删除代码
  16. UML的简单介绍和画法
  17. 志强:微商微信如何引流加人?
  18. 词云图,词频图,专门统计某些关键词的词云词频
  19. UI设计新手该怎么求职 有没有UI面试必备攻略
  20. Deepin - 磁盘清理工具Bleachbit

热门文章

  1. Linux中创建组的命令,linux创建用户组命令
  2. 要早点进入IT行业不是没道理的
  3. C++在一个类中引用另一个类的对象
  4. 一文搞定Vmware下共享文件夹
  5. 深度学习模型训练和关键参数调优详解
  6. 计算机连接打印机用户数量修改,使用注册表修改对打印机进行设置的方法
  7. Spring 01 初识 Spring
  8. MyBatis 01 快速入门
  9. 蓝桥杯嵌入式(G4系列):RTC时钟
  10. threejs 绘制球体_Three.js基础探寻四——立方体、平面与球体