This article mainly introduces how to determine the different event execution methods of mobile phones and PCs by js, so that you can determine whether the mobile phone or pc end can select the corresponding event execution function, it is a very practical technique. If you need it, you can refer to the examples in this article to describe how js judges different event execution methods on mobile phones and PCs. Share it with you for your reference. The details are as follows:
Determine whether it is a mobile phone:
function isMobile(){ var sUserAgent= navigator.userAgent.toLowerCase(), bIsIpad= sUserAgent.match(/ipad/i) == "ipad", bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os", bIsMidp= sUserAgent.match(/midp/i) == "midp", bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4", bIsUc= sUserAgent.match(/ucweb/i) == "ucweb", bIsAndroid= sUserAgent.match(/android/i) == "android", bIsCE= sUserAgent.match(/windows ce/i) == "windows ce", bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile", bIsWebview = sUserAgent.match(/webview/i) == "webview"; return (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM);}
Determine the event to use:
var touchStart,touchMove,touchEnd;touchStart = isMobile() ? 'touchstart' : 'mousedown';touchMove = isMobile() ? 'touchmove' : 'mousemove';touchEnd = isMobile() ? 'touchend' : 'mouseup';
Corresponding Handling of three types of events:
Touchstart: function (e) {var e = e | window. event; // determine which event to use stopDefault (e); // different browsers prevent different if (isMobile ()) {// for mobile phone var touch = e. touches [0]; this. y1 = touch. pageY} else {this. y1 = e. pageY; // if it is not a mobile phone} this. y2 = 0 ;}, touchmove: function (e) {var e = e | window. event; stopDefault (e); if (isMobile () {var touch = e. touches [0]; this. y2 = touch. pageY;} else {this. y2 = e. pageY ;}, touchend: function (e) {var e = e | window. event; stopDefault (e); if (this. y2 = 0) {return;} var diffY = this. y2-this.y1; if (diffY> 50) {this. doNext ();} else if (diffY <-50) {this. doPrev ();} this. y1 = 0, this. y2 = 0 ;},
Default method to prevent browser events:
function stopDefault(e){ var e=e || window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue=false; }}
I hope this article will help you design javascript programs.