博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
前端那些事之移动端常用方法
阅读量:7093 次
发布时间:2019-06-28

本文共 14290 字,大约阅读时间需要 47 分钟。

hot3.png

移动端常用的方法,相当于一个自己的小模板

常用的图片压缩成64bsae图片:

;(function (window, undefind) {    var horseFox = function () {        return new horseFox.fn.init();    };    horseFox.fn = horseFox.prototype = {        constructor: horseFox,        /*开发环境下为DEV,发布环境为PUB*/        _ENV: 'DEV',        DevParams:{            url: "test7.ttddsh.com"        },        PubParams:{            url: "www.vshowtv.com"        },        params:{},        init: function () {            /*判断如果是开发环境,用DevParams的参数;如果是发布环境,用PubParams的参数*/            if ( this._ENV === "DEV" ) {                for (var k in this.DevParams) {                    this.params[k] = this.DevParams[k];                }            } else if ( this._ENV === "PUB" ) {                for (var k in this.DevParams) {                    this.params[k] = this.PubParams[k];                }            }            return this;        }    };    horseFox.fn.init.prototype = horseFox.prototype;    /* 将私有成员和公共成员都添加extend方法*/    horseFox.extend = horseFox.fn.extend = function (obj) {        var k;        for (k in obj) {            this[k] = obj[k];        }    };    horseFox.fn.extend({        /*http请求中,显示的ui页面*/        HttpBeforeSend: function () {            console.log("hello");        },        /*获取项目信息,传参为项目参数*/        GetProjInfoNativeFunc: function (pragram) {            localStorage.setItem("pras",JSON.stringify(pragram));        }    });    /* pc&mobile */    horseFox.extend({        /*获取url参数对象,返回值为包含多个参数的对象,pc&mobile */        GetRequestPrams: function () {            var str = '',                strs = '',                url = location.search,                theRequest = new Object({});            if (url.indexOf("?") != -1) {                str = url.substr(1);                strs = str.split("&");                for(var i = 0; i < strs.length; i ++) {                    theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);                }            }            return theRequest;        },        /*获取浏览器or屏幕尺寸,返回为包含宽高的对象,pc&mobile*/        BrowserScreen:function(){            var srceenValue = {};            var height =  window.screen.height,width = window.screen.width;            srceenValue.width = width;            srceenValue.height = height;            return srceenValue;        },        /*关闭浏览器,pc*/        CloseWindow:function(){            if (navigator.userAgent.indexOf("MSIE") > 0) {                if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {                    window.opener = null;                    window.close();                }else {                    window.open('', '_top');                    window.top.close();                }            }else if (navigator.userAgent.indexOf("Firefox")>0 || navigator.userAgent.indexOf("Chrome")> 0) {                window.self.opener=null;                window.self.close();            } else {                window.opener = null;                window.open('', '_self', '');                window.self.close();            }        },        /*判断终端是pc还是mobile,返回值为number,0为pc,1为mobile,pc&mobile*/        IsWap:function(){            var motionType=0;            var sUserAgent = navigator.userAgent.toLowerCase();            var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";            var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";            var bIsMidp = sUserAgent.match(/midp/i) == "midp";            var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";            var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";            var bIsAndroid = sUserAgent.match(/android/i) == "android";            var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";            var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";            if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {                motionType=1;            }            return motionType;        },        /*获取浏览器名称,返回值为number,0是IE,1是safari,2是chrome,3是firefox,4是opera,-1是其他,pc&mobile*/        BrowserType:function(){            var userAgent = navigator.userAgent;            var isOpera = userAgent.indexOf("Opera") > -1;            if (isOpera) {                return 4;            }            if (userAgent.indexOf("Firefox") > -1) {                return 3;            }            if (userAgent.indexOf("Chrome") > -1){                return 2;            }            if (userAgent.indexOf("Safari") > -1) {                return 1;            }            if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {                return 0;            }            if (!!window.ActiveXObject || "ActiveXObject" in window) {                return 0;            }            return -1;        },        /*检查浏览器加载flash以及flash版本,返回值为对象,hasFlash为0为没有,为1是有,version是版本,pc*/        FlashCheck:function() {            var hasFlash = 0,flashVersion = 0,swf,VSwf;            if(document.all) {                swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');                if(swf) {                    hasFlash = 1;                    VSwf = swf.GetVariable("$version");                    flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);                }            } else {                if(navigator.plugins && navigator.plugins.length > 0) {                    swf = navigator.plugins["Shockwave Flash"];                    if(swf) {                        hasFlash = 1;                        var words = swf.description.split(" ");                        for(var i = 0; i < words.length; ++i) {                            if(isNaN(parseInt(words[i]))) continue;                            flashVersion = parseInt(words[i]);                        }                    }                }            }            return {                hasFlash: hasFlash,                version: flashVersion            };        },        /*文字溢出省略,传参为jquery元素和最长长度,pc&mobile*/        TextOverflowEllipsis: function (element,maxLength) {            var maxwidth = maxLength;            if ($(this).text().length > maxwidth) {                $(this).text($(this).text().substring(0, maxwidth));                $(this).html($(this).html() + '...');            }        },        /*倒计时,传入参数为任意形式的目标时间,和定时器中的回调函数,返回值定时器的执行状态,true正在执行,false为执行结束,pc&mobile*/        TimeCount: function (targetTime, callback) {            var day=0,                hour=0,                minute=0,                second=0,                miniSecond = 0,                countFlag = true,                nowTime = Date.parse(new Date()),                targetTime = Date.parse(targetTime),                intDiff = parseInt((targetTime - nowTime)/10);            var timer = setInterval(function(){                if(intDiff > 0){                    day = Math.floor(intDiff / (60 * 60 * 24 * 100));                    hour = Math.floor(intDiff / (60 * 60 *100)) - (day * 24);                    minute = Math.floor(intDiff / 60  / 100) - (day * 24 * 60) - (hour * 60);                    second = Math.floor(intDiff / 100) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);                    miniSecond = Math.floor(intDiff) - (day * 24 * 60 * 60 * 100) - (hour * 60 * 60 * 100) - (minute *60 *100) - (second * 100);                }                if (day <= 9) day = '0' + day;                if (hour <= 9) hour = '0' + hour;                if (minute <= 9) minute = '0' + minute;                if (second <= 9) second = '0' + second;                if (miniSecond <= 9) miniSecond = '0' + miniSecond;                intDiff--;                if (intDiff <= 0) {                    clearInterval(timer);                    countFlag = false;                }                callback();            }, 10);            /*倒计时结束后进来的游客看到的界面变化*/            if ( nowTime >= targetTime ) {                /*做相应的处理操作*/                countFlag = false;            }            return countFlag;        },        /*通过ajax发起网络请求,pc&mobile*/        HttpRequest: function (method, url, data, successCallback) {            $.ajax({                type: method,                url: url,                data: data,                dataType: 'json',                contentType: "application/json; charset=utf-8",                beforeSend: horseFox.HttpBeforeSend,                success: function(){                    successCallback();                },                error: function () {                    console.log('error');                },                complete: function () {                    console.log('complete');                }            });        },        /*垂直滚动滚动条,传入参数为jquery元素和元素高度,需要引入slimScroll插件,pc*/        ScrollBar: function (element, height) {            element.slimScroll({                height: height,                size: '4px',                position: 'right',                color: '#756cb7',                alwaysVisible: false,                distance: '1px',                start: 'bottom',                railVisible: true,                /* railColor: '#756cb7',*/                railOpacity: 0.3,                wheelStep: 10,                allowPageScroll: false,                disableFadeOut: false            });        },        /*点击回顶,传入参数为jquery元素,pc&mobile*/        GotoTop: function (element) {            $(window).scroll(function(){                if($(window).scrollTop()>100){                    element.fadeIn(150);                }else{                    element.fadeOut(150);                }            });            element.click(function(){                $('body,html').animate({scrollTop:0},300);                return false;            });        },        /*图片未加载出来执行的方法,传入参数为图片元素和默认图片的路径,需放在js加载完后执行,pc&mobile*/        ImgErrorHander: function (imgElement, defaultImgSrc) {            var imgUrl = imgElement.attr('src');            if ( url === undefined || url === null || url == "undefined" || url === "" ) {                imgElement.attr('src', defaultImgSrc);            }            imgElement.error(function() {                $(this).attr("src",defaultImgSrc);            });        },        /*用于监视本地存储数据的变化,传参为存储的键和回调函数,pc*/        RereshLocalData: function (key, callback) {            window.onstorage = function (e) {                if ( e.key == key) {                    callback();                }            }        }    });    // mobile    horseFox.extend({        /*获取移动终端的操作系统,mobile*/        getMobileOperatingSystem: function() {            var userAgent = navigator.userAgent || navigator.vendor || window.opera;            if (/windows phone/i.test(userAgent)) {                return "Windows Phone";            }            if (/android/i.test(userAgent)) {                return "Android";            }            if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {                return "iOS";            }            return "unknown";        },        /*设置页面js桥,mobile*/        setupWebViewJavascriptBridge: function(callback) {            if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }            if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }            window.WVJBCallbacks = [callback];            var WVJBIframe = document.createElement('iframe');            WVJBIframe.style.display = 'none';            WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';            document.documentElement.appendChild(WVJBIframe);            setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)        },        /*连接页面js桥,mobile*/        connectWebViewJavascriptBridge: function(callback) {            if (window.WebViewJavascriptBridge) {                callback(WebViewJavascriptBridge)            } else {                document.addEventListener(                    'WebViewJavascriptBridgeReady'                    , function() {                        callback(WebViewJavascriptBridge)                    },                    false                );            }        },        /*H5更新数据成功后,给客户端传递信息,mobile*/        SuccessCallBack: function() {            if (this.getMobileOperatingSystem() == 'iOS') {                this.setupWebViewJavascriptBridge(function (bridge) {                    bridge.callHandler('IsLoadingEndNativeFunc', {"IsLoadingEnd": true});                });            } else {                this.connectWebViewJavascriptBridge(function (bridge) {                    window.WebViewJavascriptBridge.callHandler('IsLoadingEndNativeFunc', {"IsLoadingEnd": true});                })            }        },        /**         * 与客户端webview的交互,mobile         * @param  {string}  registerParas    注册方法,供客户端调用         * @param  {callback}  UpdatePageJSFunc 调用方法后执行的函数         * @param  {$("div")}  ele              点击事件的元素         * @param  {string}  paras            点击后响应的方法         * @param  {obj}  parasObj          点击后传递的参数对象         * @return {Boolean}                  无返回值         */        ClientWebViewConnect: function(registerParas,UpdatePageJSFunc,ele,paras,parasObj) {            if (this.getMobileOperatingSystem() == 'iOS') {                this.setupWebViewJavascriptBridge(function (bridge) {                    bridge.registerHandler(registerParas, UpdatePageJSFunc);                    bridge.callHandler('IsLoadingEndNativeFunc', {"IsLoadingEnd": true});                    bridge.callHandler('GetProjInfoNativeFunc', null, horseFox.GetProjInfoNativeFunc);                    ele.click(function(event) {                        bridge.callHandler(paras, parasObj);                    });                });            } else {                this.connectWebViewJavascriptBridge(function (bridge) {                    bridge.init(function(message, responseCallback) {}); /*必须要*/                    bridge.registerHandler(registerParas, UpdatePageJSFunc);                    window.WebViewJavascriptBridge.callHandler('IsLoadingEndNativeFunc', {"IsLoadingEnd": true});                    window.WebViewJavascriptBridge.callHandler('GetProjInfoNativeFunc', null, horseFox.GetProjInfoNativeFunc);                    ele.click(function(event) {                        bridge.callHandler(paras, parasObj);                    });                })            }        },    })

转载于:https://my.oschina.net/yongxinke/blog/875514

你可能感兴趣的文章
首页logo的代码标志性写法,方便SEO
查看>>
Collection of Tools - Fix problems that programs cannot be installed or uninstalled
查看>>
DP+高精度 URAL 1036 Lucky Tickets
查看>>
Codeforces Round #208 (Div. 2) Problem B Dima and Text Messages(简单字符串处理)
查看>>
3D效果?
查看>>
20161028学习笔记
查看>>
浅谈UML的概念和模型之UML视图
查看>>
hive
查看>>
Jquery基础之DOM操作
查看>>
Linux系统学习笔记:文件描述符标志
查看>>
网页居中设置
查看>>
(一)学习SpringBoot介绍
查看>>
markdown2
查看>>
实验4 颜色、字符串资源的使用
查看>>
多项式求逆/分治FFT 学习笔记
查看>>
如何用CreateNewFrame() 函数创建其他视图
查看>>
创建、使用SpringBoot项目
查看>>
LinkedBlockingQueue和ArrayBlockingQueue区别
查看>>
面试题38-数字在排序数组中出现的次数
查看>>
再次总结移动端事【件穿穿透】问题
查看>>