Hbuider hybrid app开发之js常用方法

(function(w, _, $, u) {
    _.plusReady(function() {
        plus.webview.currentWebview().setStyle({
            softinputMode: "adjustResize"
        });
    });
    w.openView = function(url,extras,aniShow) {
        var showStyle = {duration: 10},waitingStyle = {autoShow: false};
//      var id = url.split('?')[0].replace(/(.*)\//g, '').split('.')[0];
        var id = url;
        showStyle.aniShow = aniShow ? aniShow : 'pop-in';
        extras = extras?extras:{};
        if (w.plus) {
            _.openWindow({
                id: id, url: url,extras:extras,styles: {popGesture: "close"},show: showStyle,waiting: waitingStyle,createNew:false
            });
        } else {
            location.href = url;
        }
    };
    w.setItem = function(key, value) {
        w.plus ? plus.storage.setItem(key, value) : localStorage.setItem(key, value);
    };
    w.getItem = function(key) {
        return w.plus ? plus.storage.getItem(key) : localStorage.getItem(key);
    };
    w.clearItem = function() {
        w.plus ? plus.storage.clear() : localStorage.clearItem();
    };
    w.removeItem = function(key) {
        w.plus ? plus.storage.removeItem(key) : localStorage.removeItem(key);
    };
    u.token = 'O]dWJ,[*g)%k"?q~g6Co!`cQvV>>Ilvw';
    //辅助工具
    u.mypost = function(app, clazz, pdata, show, success, error) {
        var sign = hex_md5(app + clazz + u.token),waiting = null;
        _.extend(true, pdata, { 'app': app, 'class': clazz, 'sign': sign });
        (w.plus && show) && _.later(function(){
            waiting = plus.nativeUI.showWaiting(show === true ? '' : show);
        },100);
        console.log(JSON.stringify(pdata));
        setTimeout(function(){
            $.ajax({
                url: "http://xxxxxx",type: "post",data: pdata,timeout:6000,
                success: function(data) {
                    waiting && waiting.close();waiting = null;
                    _.isFunction(success) ? success(data) : '';
                },
                error: function(xhr) {
                    console.log(JSON.stringify(xhr));
                    waiting && waiting.close();waiting = null;
                    _.isFunction(error) ? error() : _.toast('网络连接超时');
                }
            });
        },800);
    };
    u.urlParam = function(name) {//获取url中参数
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = location.search.substr(1).match(reg);
        return (r != null) ? decodeURIComponent(r[2]).replace('#', '') : null;
    };
    u.format = function(date, formatStr) {
        var time;
        if (typeof date == "number") time = new Date(date);
        if (date instanceof Date) time = date;
        var o = {
            "M+": time.getMonth() + 1,
            "d+": time.getDate(),
            "h+": time.getHours(),
            "m+": time.getMinutes(),
            "s+": time.getSeconds(),
            "q+": Math.floor((time.getMonth() + 3) / 3),
            "S": time.getMilliseconds()
        };
        if (/(y+)/.test(formatStr)) {
            formatStr = formatStr.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(formatStr)) {
                formatStr = formatStr.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return formatStr;
    };
    u.parse = function(date) {
        return new Date(date.replace(/-/g, "/"));
    };
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); //内存问题
    u.uuid = function(len, radix) {
        var i, r, uid = [];
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uid[i] = chars[0 | Math.random() * radix];
        } else {
            uid[8] = uid[13] = uid[18] = uid[23] = '-', uid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uid[i]) {
                    r = 0 | Math.random() * 16, uid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uid.join('');
    };
    u.call= function(){//打电话
        var btnArray = ['是','否'];
        var $tel = $("#tel"),tel = $("#tel").text()
        _.confirm('是否给“'+tel+'”进行拨号','',btnArray,function(e){
            if(e.index == 0){
                plus.device.dial(tel,false);
            }
        },'div');
    }
    u.getContacts = function(cname,cphone){//访问通讯录----@param:cname(联系人姓名dom对象);cphone(联系人电话dom对象)
        if(_.os.ios){//ios
            var contactsArr = new Array();
            var btns = ["不允许","好"];
            _.confirm('"xxxxx"要使用您的通讯录',"",btns,function(e){
                if(e.index == 1){
                    plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, function (addressbook) {
                        addressbook.find(null,function(contacts){
                            //只是获取到联系人
                            cname.val(contacts[0].displayName);
                            cphone.val("135xxxx2830");
                        }, function () {
                            _.toast("error");
                        },{multiple:true});
                    },function(e){
                        alert("Get address book failed: " + e.message);
                    });
                }
            },'div');
        }else{//android
            var btns = ["不允许","好"];
            _.confirm('"xxxx"要使用您的通讯录',"",btns,function(e){
            if(e.index == 1){
                var s_ret = null;
                var REQUESTCODE = 1000;
                main = plus.android.runtimeMainActivity();
                var Intent = plus.android.importClass('android.content.Intent');
                var ContactsContract = plus.android.importClass('android.provider.ContactsContract');
                var intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                main.onActivityResult = function(requestCode, resultCode, data) {
                  if (REQUESTCODE == requestCode) {
                    var phoneNumber = null;
                    var resultString = "";
                    var context = main;
                    plus.android.importClass(data);
                    var contactData = data.getData();
                    var resolver = context.getContentResolver();
                    plus.android.importClass(resolver);
                    var cursor = resolver.query(contactData, null, null, null, null);
                    plus.android.importClass(cursor);
                    cursor.moveToFirst();
                    var givenName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    s_ret = givenName;
                    var contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    var pCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                     null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                     null, null);
                    while (pCursor.moveToNext()) {
                        phoneNumber =   pCursor.getString( pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        s_ret += '--' + phoneNumber;
                    }
                    var rets = new Array();
                    rets = s_ret.split("--");
                    cphone.val(rets[1]);//赋值
                    cname.val(rets[0]);
                    cursor.close();
                    pCursor.close();
                  }
                };
                    main.startActivityForResult(intent, REQUESTCODE);
                }
            },'div');
        }
    };
    u.close = function(wid){//关闭webveiw
        if(w.plus){
            var thisweb = plus.webview.getWebviewById(wid);
            if(thisweb){
                console.log(thisweb.id+"   has  closed  ");
                thisweb.close();
            }
        }
    };
    var wait =60;
    u.time = function(o){//倒计时获取验证码
        if (wait == 0) {
            o.removeAttribute("disabled");
            o.textContent = "再次获取验证码";
            o.value = "再次获取验证码";
            wait = 60;
        } else {
            o.setAttribute("disabled", true);
            o.textContent = "倒计时(" + wait + "s)";
            o.value = "倒计时(" + wait + "s)";
            wait--;
            setTimeout(function() {
                time(o);
            }, 1000)
        }
    };
    u.upImg = function(self){// 拍照-选择照片添加文件 
        plus.nativeUI.actionSheet({cancel:"取消",buttons:[{title:"拍照上传"},{title:"相册选择"}]}, function(e){
            if(e.index == 0) return;
            if(e.index == 1){
                plus.camera.getCamera(1).captureImage(function(p){
                    self.src = plus.io.convertLocalFileSystemURL(p);
                });
            }else if(e.index == 2){
                plus.gallery.pick(function(p){
                    self.src = p;
                },{
                    filter:"image",multiple:false
                })
            }
        });
    };
    u.exitApp = function(){//退出应用程序
        if(plus.os.name=="Android"){
            plus.runtime.quit();
        }
    };
    w.toIndex = function(i) {
        /**
        * 跳转到首页(首页webveiw在存在的情况下)
        * 参数默认为0(首页tab bar 的第一个子页面)
        * (首页要模拟触发事件)
        * */
        var i = i || 0;//设置默认值为0 
        var idArr=["gohome","goNewPro","goMyinfo","goMycenter"];
        var main = plus.webview.getWebviewById("index.html");
        console.log("应用首页,并且切换到对应的选项卡");//显示首页
        mui.fire(main,'goIndex',{id:idArr[i]}); 
        main.show();    
    };
})(window, mui, $, window.util = {});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值