jquery项目中一些常用方法

1、获取url中的参数

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数以及解析中文乱码问题
    if (r != null) return decodeURI(r[2]); return null; //返回参数值
}

调用:getUrlParam(参数名称)    注意:参数名称是一个字符串

2、封装ajax加移动端当数据没出现出现加载图标

//封装ajax请求、
function ajax_datatypeByXml(type, url, Xml_data, func) {//data数据可以为空  
    $.ajax({
        type: type,
        url: url,
        async: false,
        dataType: "json",
        timeout: 30000, //超时时间:30秒
        data: Xml_data,
        beforeSend: function () {
            mui.showLoading("正在加载..", "div"); //加载文字和类型,plus环境中类型为div时强制以div方式显示
        },
        complete: function () {
            mui.hideLoading(function () {
            });//隐藏后的回调函数
        },
        success: function (data) {
            if (data) {
                func(data);
            } else {
                mui.alert("数据加载失败");
            }
             
        },
        error: function() {
            mui.alert('服务器连接超时,请稍后再试');
            }
    });
}
//扩展mui.showLoading
(function ($, window) {
    //显示加载框
    $.showLoading = function (message, type) {
        if ($.os.plus && type !== 'div') {
            $.plusReady(function () {
                plus.nativeUI.showWaiting(message);
            });
        } else {
            var html = '';
            html += '<i class="mui-spinner mui-spinner-white"></i>';
            html += '<p class="text">' + (message || "数据加载中") + '</p>';

            //遮罩层
            var mask = document.getElementsByClassName("mui-show-loading-mask");
            if (mask.length == 0) {
                mask = document.createElement('div');
                mask.classList.add("mui-show-loading-mask");
                document.body.appendChild(mask);
                mask.addEventListener("touchmove", function (e) { e.stopPropagation(); e.preventDefault(); });
            } else {
                mask[0].classList.remove("mui-show-loading-mask-hidden");
            }
            //加载框
            var toast = document.getElementsByClassName("mui-show-loading");
            if (toast.length == 0) {
                toast = document.createElement('div');
                toast.classList.add("mui-show-loading");
                toast.classList.add('loading-visible');
                document.body.appendChild(toast);
                toast.innerHTML = html;
                toast.addEventListener("touchmove", function (e) { e.stopPropagation(); e.preventDefault(); });
            } else {
                toast[0].innerHTML = html;
                toast[0].classList.add("loading-visible");
            }
        }
    };

    //隐藏加载框
    $.hideLoading = function (callback) {
        if ($.os.plus) {
            $.plusReady(function () {
                plus.nativeUI.closeWaiting();
            });
        }
        var mask = document.getElementsByClassName("mui-show-loading-mask");
        var toast = document.getElementsByClassName("mui-show-loading");
        if (mask.length > 0) {
            mask[0].classList.add("mui-show-loading-mask-hidden");
        }
        if (toast.length > 0) {
            toast[0].classList.remove("loading-visible");
            callback && callback();
        }
    }
})(mui, window);

3、初始化移动端根节点字体大小用作rem值

window.addEventListener("resize", setSize, false);
window.addEventListener("orientationchange", setSize, false);
function setSize() {
    var oHtml = document.getElementsByTagName("html")[0];
    var iWidth = oHtml.getBoundingClientRect().width;
    $("html").css("fontSize", iWidth / 15)
}

4、根据年月获得当月天数的实现代码

function getDaysInMonth(year, month) {
    month = parseInt(month, 10);
    var temp = new Date(year, month, 0);
    return temp.getDate();
}

5、屏蔽打印console

console.log=function(){}

6、当动态生成li时点击事件有时可能会触发两次解决办法

$('body').off('click').on('click','selector',function(){});

使用之前要清理掉body上绑定的click事件,利用了jQuery里面off()方法

7、择input框的选中状态操作

<div class="desc">
   <input type="checkbox" id="selectAll" onclick="checkAll()">全选
</div>
<script>
  function checkAll()
{
var checkedOfAll=$("#selectAll").prop("checked");
$("input[name='procheck']").prop("checked", checkedOfAll);
alert(checkedOfAll);
}
</script>

8、鼠标移入移出事件并在移入时操作

  $(".contactus-wrap").mouseover( function () {
                   clearTimeout(time);
                    $(".contactus").css({
                        "opacity": 1,
                        "left":"12px"
                    })
                });
            $(".contactus-wrap").mouseout(
                function () {
                    time = setTimeout(function () {
                        $(".contactus").css({
                            "opacity": 0,
                            "left": "-206px"
                        })
                    }, 500)
                });
            $(".contactus").mouseover(function () {
                clearTimeout(time); $(".contactus").css({
                    "opacity": 1,
                    "left": "12px"
                })
            });
            $(".contactus").mouseout(function () {
                time = setTimeout(function () {
                    $(".contactus").css({
                        "opacity": 0,
                        "left": "-206px"
                    })
                }, 500);
            });

 9、jquery中获取父级iframe中的dom元素

$(parent.window.document).find("iframe").contents().find("#F_HTNO");

10、textarea自动换行,且文本框根据输入内容自适应高度

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>输入框自适应</title>
    <script src="jquery.min.js"></script>
    <script>
        // textare自动换行
     /**
     * 文本框根据输入内容自适应高度
     * @param                {HTMLElement}        输入框元素
     * @param                {Number}                设置光标与输入框保持的距离(默认0)
     * @param                {Number}                设置最大高度(可选)
     */
     var autoTextarea = function (elem, extra, maxHeight) {
             extra = extra || 0;
             var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window,
             isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'),
                     addEvent = function (type, callback) {
                             elem.addEventListener ?
                                     elem.addEventListener(type, callback, false) :
                                     elem.attachEvent('on' + type, callback);
                     },
                     getStyle = elem.currentStyle ? function (name) {
                             var val = elem.currentStyle[name];
     
                             if (name === 'height' && val.search(/px/i) !== 1) {
                                     var rect = elem.getBoundingClientRect();
                                     return rect.bottom - rect.top -
                                             parseFloat(getStyle('paddingTop')) -
                                             parseFloat(getStyle('paddingBottom')) + 'px';        
                             };
     
                             return val;
                     } : function (name) {
                                     return getComputedStyle(elem, null)[name];
                     },
                     minHeight = parseFloat(getStyle('height'));
     
             elem.style.resize = 'none';
     
             var change = function () {
                var scrollTop, height,
                        padding = 0,
                        style = elem.style;

                if (elem._length === elem.value.length) return;
                elem._length = elem.value.length;

                if (!isFirefox && !isOpera) {
                        padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
                };
                scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

                elem.style.height = minHeight + 'px';
                if (elem.scrollHeight > minHeight) {
                        if (maxHeight && elem.scrollHeight > maxHeight) {
                                height = maxHeight;
                                style.overflowY = 'auto';
                        } else {
                                height = elem.scrollHeight;
                                style.overflowY = 'hidden';
                        };
                        style.height = height + extra + 'px';
                        // scrollTop += parseInt(style.height) - elem.currHeight;
                        // document.body.scrollTop = scrollTop;
                        // document.documentElement.scrollTop = scrollTop;
                        elem.currHeight = parseInt(style.height);
                };
             };
     
             addEvent('propertychange', change);
             addEvent('input', change);
             addEvent('focus', change);
             change();
     };
     
     
     
    $(document).ready(function() {
      $("table td").each(function() {
             if ($(this).find("[datatype='required']").length > 0||$(this).find("[datatype='number']").length > 0) {
                 $(this).css("position", "relative");
             }
     })
    })
     
     </script>
</head>
<body>
   <table>
       <tr>
        <td>
            <textarea datatype="required" id="grxygzjh"
            isheightauto="true" maxlength="1000" 
            msg="必填项" name="grxygzjh" onfocus="autoTextarea(this)"
            placeholder="*请输入个人下月工作计划" 
            style="width:99%; font-size: 15px; border-style: none none solid; border-color: rgb(255,255, 255) rgb(255, 255, 255) rgb(119, 119, 119);
             border-bottom-width: 1px;height: 39px; background: transparent; text-align:left"
             type="text">
            </textarea></td>
       </tr>
   </table> 
</body>
</html>

 11、移动端悬浮按钮可拖动

 touchImg: function () {
                var flag = 0; //标记是拖曳还是点击
                var oDiv = document.getElementsByClassName('add-btn')[0];
                var disX,moveX,L,T,starX,starY,starXEnd,starYEnd;
                oDiv.addEventListener('touchstart',function(e){
                    flag = 0;
                    e.preventDefault();//阻止触摸时页面的滚动,缩放
                    disX = e.touches[0].clientX - this.offsetLeft;
                    disY = e.touches[0].clientY - this.offsetTop;
                    //手指按下时的坐标
                    starX = e.touches[0].clientX;
                    starY = e.touches[0].clientY;
                    //console.log(disX);
                });
                oDiv.addEventListener('touchmove',function(e){
                    flag = 1;
                    L = e.touches[0].clientX - disX ;
                    T = e.touches[0].clientY - disY ;
                    //移动时 当前位置与起始位置之间的差值
                    starXEnd = e.touches[0].clientX - starX;
                    starYEnd = e.touches[0].clientY - starY;
                    //console.log(L);
                    if(L<0){//限制拖拽的X范围,不能拖出屏幕
                        L = 0;
                    }else if(L > document.documentElement.clientWidth - this.offsetWidth){
                        L=document.documentElement.clientWidth - this.offsetWidth;
                    }
                    if(T<0){//限制拖拽的Y范围,不能拖出屏幕
                        T=0;
                    }else if(T>document.documentElement.clientHeight - this.offsetHeight){
                        T = document.documentElement.clientHeight - this.offsetHeight;
                        console.log(T)
                    }
                    moveX = L + 'px';
                    moveY = T + 'px';
                    //console.log(moveX);
                    this.style.left = moveX;
                    this.style.top = moveY;
                });
                window.addEventListener('touchend',function(e){
                    //alert(parseInt(moveX))
                    //判断滑动方向
                    if(flag === 0) {//点击
                       
                    }
                });
            }
          }

 12、监听input中value改变

 //监听input中value改变
        var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;//浏览器兼容
        var config = { attributes: true, childList: true }//配置对象
        $("input").each(function () {
            var _this = $(this);
            var observer = new MutationObserver(function (mutations) {//构造函数回调
                mutations.forEach(function (record) {
                    if (record.type == "attributes") {//监听属性
                        window.location.reload();
                    }
                    if (record.type == 'childList') {//监听结构发生变化
                       
                        //do any code
                    }
                });
            });
            observer.observe(_this[0], config);
        });

 13、监听多张图片加载完成

 $.when.apply(null, $(".ccc").map(function(i, e) {
        var dfd = $.Deferred();
        if (e.complete) {
           console.log(`${i}`)
            dfd.resolve()
        } else {
            e.onload = function() {
                console.log(`${i}`)
                dfd.resolve()
            }
        }
        return dfd;
    }).toArray()).done(function() {
        console.log("图片加载完成");
         //要执行的方法loop();

    });
        console.log("图片开始加载");

 14、在不屏蔽F12的情况下禁止用户修改网页

  var submitBtn = parent.document.getElementById("lbtnPrint");
    var blackLbtnPrint = parent.document.getElementById("blacklbtnPrint");
    if ($(submitBtn).length > 0 || $(blackLbtnPrint).length > 0) {
        var ConsoleManager = {
            onOpen() {
                $(submitBtn).hide();
                $(blackLbtnPrint).hide();
                // alert("Console is opened")
            },
            onClose() {
                window.parent.location.reload();
                $(submitBtn).show();
                $(blackLbtnPrint).show();
                // alert("Console is closed")
            },
            init() {
                var self = this;
                var x = document.createElement('div');
                var isOpening = false, isOpened = false;
                Object.defineProperty(x, 'id', {
                    get() {
                        if (!isOpening) {
                            self.onOpen();

                            isOpening = true;

                        }
                        isOpened = true;
                    }
                });
                setInterval(function () {
                    isOpened = false;
                    console.info(x);
                    console.clear();
                    if (!isOpened && isOpening) {
                        self.onClose();
                        isOpening = false;
                    }
                }, 200)
            }
        }
        ////如果f12打开就隐藏打印按钮
        ConsoleManager.onOpen = function () {

            $(submitBtn).hide();
            $(blackLbtnPrint).hide();
           // alert("Console is opened!!!!!")
        }
        ConsoleManager.onClose = function () {
            window.parent.location.reload();
            $(submitBtn).show();
            $(blackLbtnPrint).show();

            // alert("Console is closed!!!!!")
        }
        ConsoleManager.init();
    }

 15、iframe在移动端的缩放的示例代码

 //缩放ifrmae页面
                var Width = document.body.scrollWidth;
                var Height = document.body.scrollHeight;
                var zoomScale = Width / 640;
                setTimeout(function () {
                    console.log($("#ifr"))
                    $("#ifr").css({
                        "transform": "scale(" + zoomScale + ")",
                        "width": (Width / zoomScale),
                        "height": (Height / zoomScale),
                        "transform-origin": "0 top 0"
                    });

                }, 1000)

 

posted @ 2018-06-27 18:12  零碎沉默  阅读(282)  评论(0编辑  收藏  举报