js 小操作

获取上一个页面的url
console.log(document.referrer)
页面关闭之前触发的函数

window.onbeforeunload=function(e){     
  //你想要做什么??
} 

禁止手机端左滑触发浏览器后退

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

数组截取

var arr=[1,2,3,4,5,6,7,8,9,10,11];
arr.slice(0,10)//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

时间转换

Date.prototype.Format = function (fmt) {
        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("yyyy-MM-dd");//2019-02-25
    var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");//2019-02-25 16:02:01

解决移动端300ms
[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive
有时候在移动端使用 滑动事件的时候,会出现这个报错,主要是因为 移动端点击事情会有300ms的延迟,所以在css样式中加一个* { touch-action: none; }CSS属性 touch-action用于指定某个给定的区域是否允许用户操作,以及如何响应用户操作(比如浏览器自带的划动、缩放等)。

单行文本超出显示省略号

overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
width:100%;

jQuery获取option的文本值和value值

$('#carTypeChoose').change(function () {
    var text=$('#carTypeChoose option:selected').text();
    var value=$(this).val();
});

jquery实时监听input输入框值的变化事件

$('#input').bind('input propertychange', function(){
    console.log($(this).val())
})
//但这并不完美,因为用的bind,所以当遇到追加的新input标签时,则不能监听了。

$('#input').live('input propertychange', function(){
    console.log($(this).val())
})

多行文本超出显示省略号
适用webkit内核和移动端浏览器

width:100%;
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;  //这里是在第二行有省略号

禁止ios用户缩放页面
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
图片居中显示
父元素
position:relative;
图片

position:absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);

利用css实现简单的左右滑动

<div> 
   <ol>
      <li>
    <img src={imgurl} alt=''/>
     </li>
      <li>
    <img src={imgurl} alt=''/>
     </li>
     <li>
    <img src={imgurl} alt=''/>
     </li>               
   </ol>
</div>
ol{
    overflow-x: auto;
    overflow-y: hidden;
    padding-left: 20px;
    white-space: nowrap;
}
li{
    list-style: none;
    display: inline-block;
    vertical-align: top;
    white-space: normal;
    margin:0 10px;
}
img{
    display: block;
    width:100px;
    height:100px;
}

网页上方插入图标 写在Head里面
<link href="/images/favicon.ico" rel="shortcut icon" />
阻止事件冒泡
event.preventDefault();
event.stopPropagation()
在ios设备上,在登录页面输入文本框导致页面滚动条不回弹

$('#login_password').blur(function(){
    window.scrollTo(0,scroll);
});

过滤
描述:<input>框输入内容,过滤掉其他集体渲染的<li>标签

$(".searchcell_input").on("focus", function() {
    var that = $(this);
    //显示列表
    $(".choosecell_box ul").show();
    //输入实时查询事件,propertychange是IE的输入监听事件,input是其它浏览器
    $(".searchcell_input").on("input propertychange", function() {
        $(".choosecell_box ul li").hide().filter(":contains('" + that.val().toLocaleLowerCase() + "')").show(); //小写
    });
});

jQuery封装的ajax会将数组转化为字符串
描述:如果需要传入后台的数据是数组的话

data: {
    ids:JSON.stringify(billIdArr) ,
},

判断ajax请求成功

$(document).ajaxComplete(function(){
    //所有页面中有很多个请求 这个回调就会至少多次
})

回到顶部

var isClick=true;
$('.backup').click(function(){
    if(isClick){
        var scrollToTop=setInterval(function(){
            isClick=false;
            var pos = window.pageYOffset;
            if ( pos > 0 ) {
                window.scrollTo( 0, pos - 100 ); // how far to scroll on each step
            } else {
                window.clearInterval( scrollToTop );
                isClick=true;
            }
        },16)
    }
});

移动端点击事件失效,iphonex的小条遮挡住底部的点击事件
可以将click事件改为touchstart事件
touchstart事件:当按下手指时触发该事件
数组去重
1.如果newArr里面没有就push

var arr = [1,2,3,4,1,1,2,4,4];
   var newArr=[];
   for(var i=0;i<arr.length;i++){
        if(newArr.indexOf(arr[i])===-1){
         newArr.push(arr[i])
   }
console.log(newArr)//[1,2,3,4]

2.将一个类数组对象或者可遍历对象转换成一个真正的数组,必须要有length属性

var arr = [1,2,3,4,1,1,2,4,4];
arr = Array.from(new Set(arr))//[1,2,3,4]

3.利用indexOf()方法,如果indexOf()的值与i相等,就表明是第一次出现

var arr = [1,2,3,4,1,1,2,4,4];
   var newArr=[];
   for(var i=0;i<arr.length;i++){
        if(arr.indexOf(arr[i])===i){
           newArr.push(arr[i])
       }
  }
console.log(newArr);//[1,2,3,4]

将this is a pen四个单词首字母大写

var a='this is a pen';
var arr=a.split(' ');
var newArr=[];
for(var i=0;i<arr.length;i++){
     newArr.push(arr[i].slice(0,1).toUpperCase()+arr[i].slice(1))
}
console.log(newArr.join(' '))//This Is A Pen

关于浏览器的各种距离
浏览器可视区域的高度window.innerHeight
浏览器可视区域的宽度window.innerWidth
滚动条滚动的距离document.documentElement.scrollTop || document.body.scrollTop
元素距离顶部的高度offsetTop
元素距离左边的距离offsetLeft
在ios或者某些华为机型中会出现input不让输入的问题

-webkit-user-select: auto;
-moz-user-select: auto;

安卓ios打开摄像头
<input type='file' accept="image/*" mutiple="mutiple" capture="camera" />
iphone5媒体查询

@media  screen and (max-width: 320px){
  /* css code*/
}

iphone6/7/8媒体查询

@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (-webkit-device-pixel-ratio: 2) {
      /* css code*/
}

iphone6/7/8 plus媒体查询

@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (-webkit-device-pixel-ratio: 3) {
  /* css code*/
}

iphoneX iphoneXS媒体查询

@media only screen and (device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) {
  /* css code*/
}

iphoneXR媒体查询

@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio:2) {
  /* css code*/
}

iphoneXS Max媒体查询

@media only screen and (device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio:3) {
  /* css code*/
}

引入外部字体

@font-face {
    font-family: 'lantingheijian';//字体名字
    src:url("../lthj.TTF");//字体路径
}
.branchList p{
    font-family: lantingheijian;//直接使用
}

手机号码正则表达式

//第一位是【1】开头,第二位则则有【3,4,5,7,8】,第三位则是【0-9】,第三位之后则是数字【0-9】。
let phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
//如果第二位改为了6啊 9什么的 就不验证第二位
var reg = /^1[0-9]{10}$/;

调整input框提示信息的样式

input::-webkit-input-placeholder {
    color: #FFB988;
    font-size: 14px;
}

检测用户手机竖屏横屏

window.addEventListener("onorientationchange" in window? "orientationchange":"resize",function(){
    setTimeout(function(){
        if(window.orientation===0 || window.orientation===180){
            //竖屏模式
        }
        if(window.orientation===90  ||  window.orientation===-90){
            //横屏模式
        }
    },300)
},false);

生成特定网站的二维码
首先引入qrcode.js

var qrcode = new QRCode('qrcode', { // qrcode为id  页面上需要有一个容器 id为qrcode来装载这个二维码
     text: 'http://rbpicc.d.vipgogo.com/index/Notice/piccVip',
});

解决移动端1px的渲染问题

Renita屏幕上,会将1px的边框渲染成2px 所以需要处理一下

.border { border: 1px solid #999 }
@media screen and (-webkit-min-device-pixel-ratio: 2) {
    .border { border: 0.5px solid #999 }
}
@media screen and (-webkit-min-device-pixel-ratio: 3) {
    .border { border: 0.333333px solid #999 }
}

li只能点击一次

//加一个这个class 
.disable {
    pointer-events: none;
}

函数节流

//比如 一个搜索框 用户输入需要一直
let timer;
$('.i1').bind('input propertychange', function(){
    let value=$(this).val();
    clearTimeout(timer);
    timer = setTimeout(function() {
        // 执行具体代码
        console.log(1111)
    }, 500)
})

css检测横屏

@media screen and (orientation: portrait) {
  /*竖屏...*/
} 
@media screen and (orientation: landscape) {
  /*横屏...*/
}

js检测横屏

window.addEventListener("resize", ()=>{
    if (window.orientation === 180 || window.orientation === 0) {
        // 正常方向或屏幕旋转180度
        console.log('竖屏');
    };
    if (window.orientation === 90 || window.orientation === -90 ){
        // 屏幕顺时钟旋转90度或屏幕逆时针旋转90度
        console.log('横屏');
    }
})

文本两端对齐

<ul id="u1">
    <li>姓名</li>
    <li>手机号码</li>
    <li>账号</li>
</ul>
#u1 li{
    text-align: justify;
    text-align-last:justify;
    border: 1px solid red;
}
效果图

微信公众号页面播放音频

因为在ios中 开始播放需要用点击事件来触发

document.addEventListener("WeixinJSBridgeReady", function () {
       document.getElementById('mp3').play();
}, false);

上传照片 可以打开摄像头+相册选择

<a href=" " class="upload" id="upload2">
    <input class="upload" name="upimg" type="file" id="file2" accept="image/*"/>
</a>
$("#upload2").on("change", function(e) {
      //获取图片资源
      jiaban1(e);
});
function jiaban1(e){
    $('#loading').css({
        'display':'flex'
    });
    file2 = e.target.files[0];
    if(file2.size>10000000){
        toast('图片太大啦!');
        return false;
    }
    var uploadimg=$('#file2').val();
    if(uploadimg==''){
        toast('请选择文件');
        return false;
    }
    var formData = new FormData();
    formData.append('upimg', $('#file2')[0].files[0]);
    $.ajax({
        url: '/AnswerRush/upImg',
        type: 'POST',
        data: formData,
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        success: function (res) {
            if(res.code==='1'){
                $('.clickUploadImg').attr('src',`${res.url}`);
                $('#loading').css({
                    'display':'none'
                });
                toast('上传成功,再次点击照片可更换照片');
                $('.imgDiv').attr('isUpload','1')
            }else{
                toast(res.msg);
            }
        },
        error:function (res) {
            alert(JSON.stringify(res));
            toast('系统错误');
        }
    });
}

禁止微信分享

//禁止微信分享
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(); 
}

canvas生成的二维码微信无法识别

function convertCanvasToImage(canvas) {
    //新Image对象,可以理解为DOM
    var image = new Image();
    // canvas.toDataURL 返回的是一串Base64编码的URL,当然,浏览器自己肯定支持
    // 指定格式PNG
    image.src = canvas.toDataURL("image/png");
    return image;
}
//获取网页中的canvas对象
var mycanvas1=document.getElementsByTagName('canvas')[0];
//将转换后的img标签插入到html中
var img = convertCanvasToImage(mycanvas1);
$('#qrcode').append(img);//imgDiv表示你要插入的容器id

引入MUI的三级联动

<link rel="stylesheet" href="/kxf/common/css/mui.picker.css">
<link rel="stylesheet" href="/common/css/mui.poppicker.css">
<script src="/common/js/mui.min.js"></script>
<script src="/common/js/mui.picker.js"></script>
<script src="/common/js/mui.poppicker.js"></script>

var adressPicker=new mui.PopPicker({
    layer: 3
});
adressPicker.setData(cityData3);
$('.adressDiv').click(function(){
    adressPicker.show(function(items) {
        let adress=items[0].text+''+items[1].text+''+items[2].text;
        $(".adress").val(adress)
    });
})

截取url上的参数

用的时候直接调用方法传入参数就可以了 getQueryVariable('userId')

function getQueryVariable(variable){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] ===variable){return pair[1];}
    }
    return(false);
}

取的参数中文会乱码
decodeURI()
mui使用时间选择器
mui.min.js mui.picker.min.js
mui.picker.min.css以及自己添加的样式

/*mui 时间选择器后加入的样式*/
.mui-h5, h5 {
    font-size: 14px;
    font-weight: 400;
    color: #8f8f94;
}
.mui-btn{
    font-size: 14px;
    font-weight: 400;
    line-height: 1.42;
    position: relative;
    display: inline-block;
    margin-bottom: 0;
    padding: 6px 12px;
    cursor: pointer;
    -webkit-transition: all;
    transition: all;
    -webkit-transition-timing-function: linear;
    transition-timing-function: linear;
    -webkit-transition-duration: .2s;
    transition-duration: .2s;
    text-align: center;
    vertical-align: top;
    white-space: nowrap;
    color: #333;
    border: 1px solid #ccc;
    border-radius: 3px;
    background-color: #fff;
    background-clip: padding-box;
}
.mui-btn-blue, .mui-btn-primary, input[type=submit] {
    color: #fff;
    border: 1px solid #007aff;
    background-color: #007aff;
}
.mui-dtpicker-title{
    display: flex;
    box-sizing: border-box;
}

js部分

//唤出时间选择器
$('.dieTimeDiv').click(function(){
    let optionsJson=$(this).attr('data-options')||"{}";
    let options = JSON.parse(optionsJson);
    var picker = new mui.DtPicker(options);
    picker.show(function(res) {
        $('.dieTime').val(res.value)
        picker.dispose();
    });
});

form表单序列化

function paramSerialize(param){
    //form表单参数序列化
    let data=param;
    let dataArr=data.split('&');
    let dataObj={};
    for(let i=0;i<dataArr.length;i++){
        let objArr=dataArr[i].split('=');
        let obj={
            [objArr[0]]:objArr[1]
        };
        Object.assign(dataObj,obj)
    }
    return dataObj;
}

安卓手机input框会挤压视图

let Height = $('body').height();
$(window).resize(function() {
   $('body').height(Height);
});

--------------------------------------------------永久更新--------------------------------------------------------

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  •   JavaScript 与 HTML 之间的交互是通过事件实现的。   事件,就是文档或浏览器窗口中发生的一些特...
    霜天晓阅读 3,752评论 1 11
  • 1.几种基本数据类型?复杂数据类型?值类型和引用数据类型?堆栈数据结构? 基本数据类型:Undefined、Nul...
    极乐君阅读 5,931评论 0 106
  • JavaScript 与 HTML 之间的交互是通过事件实现的。事件,就是文档或浏览器窗口中发生的一些特定的交互瞬...
    LemonnYan阅读 766评论 0 4
  • 第3章 基本概念 3.1 语法 3.2 关键字和保留字 3.3 变量 3.4 数据类型 5种简单数据类型:Unde...
    RickCole阅读 5,606评论 0 21
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 29,144评论 1 45

友情链接更多精彩内容