JavaScript +微信公众号 笔记(2021-08-25)

1、问题:弹出输入法的时候页面底部按钮被顶上去了

监听页面大小变化

.voteFootDiv {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #ffffff;
}
$(window).resize(function (event) {
    if ('fixed' === $(".voteFootDiv").css('position')) {
        $(".voteFootDiv").css('position', 'static')
    } else {
        $(".voteFootDiv").css('position', 'fixed')
    }
});

2、DOM变化监听事件:https://www.cnblogs.com/xiaohuochai/p/5873289.html

$("#domIDname").bind('DOMNodeInserted',function(e){
            console.log(123);    
    });

3、页面/DOM的滚动事件

<script>
        <!--div滚动触发-->
        window.onscroll = function () {
            //获取div距离顶部的距离
            var divH1 = document.getElementById("divID").offsetTop;
            //获取div高度
            var divH2 = parseInt(document.getElementById("divID").style.height);
            //屏幕卷去的高度
            var scrollTops = document.body.scrollTop || document.documentElement.scrollTop;
            //屏幕卷去的高度>div距离顶部的高度和div本身的高度的总和
            if (scrollTops > (divH1 + divH2)) {
                console.log('show');
            } else {
                console.log('hide');
            }
        }
</script>

4、获取设备屏幕高度

 var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
 var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
 $(".wq1").css("width", w + "px").css("height", h + "px");//全屏显示

5、H5摇一摇:(大神地址待补充)

 function shakeListener() {
    const SHAKE_SPEED = 300;
    var lastTime = 0;//上次变化的时间
    var x = y = z = lastX = lastY = lastZ = 0;//位置变量初始化
    function motionHandler(event) {
        var acceleration = event.accelerationIncludingGravity;
        var curTime = Date.now();//取得当前时间
        if ((curTime - lastTime) > 120) {
            var diffTime = curTime - lastTime;
            lastTime = curTime;
            x = acceleration.x;
            y = acceleration.y;
            z = acceleration.z;
            //计算摇动速度
            var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 1000;
            if (speed > SHAKE_SPEED) {
                shake_result();
            }
            lastX = x;
            lastY = y;
            lastZ = z;
        }
    }

    if (window.DeviceMotionEvent) {
        window.addEventListener('devicemotion', motionHandler, false);
    } else {
        alert2s("您的设备不支持摇一摇感应");
    }
}

6、子节点选择 filter
  

  $("ul").children(".classname")

7、冒泡和捕捉

//事件捕获
    dom_obj.onclick = function(e){
      e = e || event;//兼容性
      e.stopPropagation();//阻止冒泡,但不阻止其他的监听
      e.stopImmediatePropagation();//阻止冒泡,阻止监听
      e.cancelBubble = true;//可读写,true阻止冒泡,false不阻止
  }
//冒泡兼容性:
    var handler = function(e){
          e = e || event;
          if(e.stopPropagation){
              e.stopPropagation();
          }else{
              e.cancelBubble = true;
          }
  }
//取消默认行为:
       e.preventDefault();
       e.returnValue = false;
       return false;
//取消默认兼容性:
      var handler = function(e){
          e = e || event;
          if(e.preventDefault){
              e.preventDefault();
          }else{
              e.returnValue = false;
          }
      }

8、promise的用法例子:红绿灯顺序延时(大神地址:https://www.cnblogs.com/dojo-lzz/p/5495671.html)     

//业务函数
function red() {
  console.log('red');
}

function green() {
  console.log('green');
}

function yellow() {
  console.log('yellow');
}

//配置promise函数1
var tic = function (timmer, func) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      func();
      resolve();
    }, timmer);
  });
};

//配置promise函数2
var d = new Promise(function (resolve, reject) {
  resolve();
});

//配置函数顺序
var step = function (def) {
  def.then(function () {
      return tic(1000, red);
    }).then(function () {
      return tic(2000, green);
    }).then(function () {
      return tic(3000, yellow);
    }).then(function () {
      console.log("=====");
    step(def);
  });
}

//执行函数
step(d);

9、小知识:

//String比较:
可以直接比较if(s1>s2);原理就是按照unicode的顺序,从index下标0开始比较的

//禁用右键上下文菜单
$(document).bind('contextmenu',function(e){return false;});

//判断一个元素是否可见
if(   $('#id1').is(':visible')    )

//判断是否包含一个类名--用于全选之后触发判断
$("idDiv").hasClass("className1");

//切换类名
$(this).toggleClass('riskImg1');//切换添加/删除类名—— 就是两个函数切换使用addClass  removeClass

//下拉菜单取值
$('select:selected').text()

  //Number的函数
  n.toFixed(2) //指定小数位
  n.toPrecision(2) //指定有效位数

 

 

 

 10、日期格式

  // 对Date的扩展,将 Date 转化为指定格式的String
    // 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
    // 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
    // 例子: 
    // (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
    // (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
    
    
    Date.prototype.Format = function (fmt) { //author: meizz 
        var o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //
            "s+": this.getSeconds(), //
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }

//调用:

var time1 = new Date().Format("yyyyMMdd");比较时间的时候可以之间比较大小if(d1>d2)
var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");

11、页面css和js添加版本号:https://www.cnblogs.com/dongxiaolei/p/6374797.html

$("link,script").each(function(){
                var t=Math.random().toFixed(4);
                /*var $tag=$(this).prop("tagName").toLowerCase();//获取当前元素的标签名
                if($tag == "link"){
                    var $href=$(this).attr("href");
                    $(this).attr("href",$href+"?v="+t)
                }else{
                    if(typeof($(this).attr("src")) != "undefined"){//判断script标签有没有src属性
                        var $src=$(this).attr("src");
                         $(this).attr("src",$src+"?v="+t)
                    }
                }*/
                if($(this).attr("src")){
                    var $src=$(this).attr("src");
                    $(this).attr("src",$src+"?v="+t)
                }else if($(this).attr("href")){
                    var $href=$(this).attr("href");
                    $(this).attr("href",$href+"?v="+t)
                }
            })

12、金额大小写切换

function DX() {
        var n = $("#bigInput").val();
        var bigData;
        if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
            bigData = "数据非法";
        } else {
            var unit = "仟佰拾亿仟佰拾万仟佰拾元角分", str = "";
            n += "00";
            var p = n.indexOf('.');
            if (p >= 0)
                n = n.substring(0, p) + n.substr(p + 1, 2);
            unit = unit.substr(unit.length - n.length);
            for (var i = 0; i < n.length; i++)
                str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
            bigData = str.replace(/零(仟|佰|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(壹拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
        }
        $("#bigData").text(bigData);
    }

13、随机密码

function randomPWD(len) {
        var str = "",
            arr1 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
            arr2 = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

        for (var i = 0; i < len/2; i++) {
            pos = Math.round(Math.random() * (arr1.length - 1));
            str += arr1[pos];
        }
        for (var i = 0; i < len/2; i++) {
            pos = Math.round(Math.random() * (arr2.length - 1));
            str += arr2[pos];
        }
        return str;
    }

14、返回键监听

<script>
            //monitor back btn
            pushHistory();
            function pushHistory() {
                var state = {
                    title: "title",
                    url: "#"    };
                window.history.pushState(state, "title", "#");
            }
            window.onpopstate = function() {
              if($("#footPopRisk").css("display")!="none"){
                  $("#footPopRisk").hide();
                  return false;
              }else{
                  back();
              }
            };
            //end
        </script>

//返回上一页:

//self.location= document.referrer;
var documentReferrer = document.referrer;
var locationDocumentReferrer = documentReferrer;
if (!isNull(documentReferrer)) {
  localStorage.documentReferrer = documentReferrer;
}
locationDocumentReferrer = localStorage.documentReferrer;
self.location = locationDocumentReferrer;

//---综合上面的返回监听返回----
<script>
  //monitor back btn
  pushHistory();
  function pushHistory() {
    var state = {
    title: "title",
    url: "#" };
    window.history.pushState(state, "title", "#");
  }


  window.onpopstate = function() {
    var documentReferrer = document.referrer;
    var locationDocumentReferrer = documentReferrer;
    if (!isNull(documentReferrer)) {
        localStorage.documentReferrer = documentReferrer;
    }
    locationDocumentReferrer = localStorage.documentReferrer;
    self.location = locationDocumentReferrer;
  };
</script>

15、

 

 

*****************************

**********  微信  *********

*****************************

微信开发者文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

微信js地址:http://res.wx.qq.com/open/js/jweixin-1.6.0.js

1、关闭微信浏览器:直接调用即可

WeixinJSBridge.call('closeWindow');

2、禁止页面分享:直接执行即可

 <script>
        function onBridgeReady() {
            WeixinJSBridge.call('hideOptionMenu');
        }
    
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady();
        }
    </script>

3、

 

posted @ 2018-09-21 15:08  桦屋飘蓬  阅读(691)  评论(0编辑  收藏  举报