獲取上一個(gè)頁面的url
console.log(document.referrer)
頁面關(guān)閉之前觸發(fā)的函數(shù)
window.onbeforeunload=function(e){
//你想要做什么??
}
禁止手機(jī)端左滑觸發(fā)瀏覽器后退
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
數(shù)組截取
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]
時(shí)間轉(zhuǎn)換
Date.prototype.Format = function (fmt) {
var o = {
"M+": this.getMonth() + 1, // 月份
"d+": this.getDate(), // 日
"h+": this.getHours(), // 小時(shí)
"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;
};
//調(diào)用
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
解決移動(dòng)端300ms
[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive
有時(shí)候在移動(dòng)端使用 滑動(dòng)事件的時(shí)候,會(huì)出現(xiàn)這個(gè)報(bào)錯(cuò),主要是因?yàn)?移動(dòng)端點(diǎn)擊事情會(huì)有300ms的延遲,所以在css樣式中加一個(gè)* { touch-action: none; },CSS屬性 touch-action用于指定某個(gè)給定的區(qū)域是否允許用戶操作,以及如何響應(yīng)用戶操作(比如瀏覽器自帶的劃動(dòng)、縮放等)。
單行文本超出顯示省略號
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實(shí)時(shí)監(jiān)聽input輸入框值的變化事件
$('#input').bind('input propertychange', function(){
console.log($(this).val())
})
//但這并不完美,因?yàn)橛玫腷ind,所以當(dāng)遇到追加的新input標(biāo)簽時(shí),則不能監(jiān)聽了。
$('#input').live('input propertychange', function(){
console.log($(this).val())
})
多行文本超出顯示省略號
適用webkit內(nèi)核和移動(dòng)端瀏覽器
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實(shí)現(xiàn)簡單的左右滑動(dòng)
<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;
}
網(wǎng)頁上方插入圖標(biāo) 寫在Head里面
<link href="/images/favicon.ico" rel="shortcut icon" />
阻止事件冒泡
event.preventDefault();
event.stopPropagation()
在ios設(shè)備上,在登錄頁面輸入文本框?qū)е马撁鏉L動(dòng)條不回彈
$('#login_password').blur(function(){
window.scrollTo(0,scroll);
});
過濾
描述:<input>框輸入內(nèi)容,過濾掉其他集體渲染的<li>標(biāo)簽
$(".searchcell_input").on("focus", function() {
var that = $(this);
//顯示列表
$(".choosecell_box ul").show();
//輸入實(shí)時(shí)查詢事件,propertychange是IE的輸入監(jiān)聽事件,input是其它瀏覽器
$(".searchcell_input").on("input propertychange", function() {
$(".choosecell_box ul li").hide().filter(":contains('" + that.val().toLocaleLowerCase() + "')").show(); //小寫
});
});
jQuery封裝的ajax會(huì)將數(shù)組轉(zhuǎn)化為字符串
描述:如果需要傳入后臺(tái)的數(shù)據(jù)是數(shù)組的話
data: {
ids:JSON.stringify(billIdArr) ,
},
判斷ajax請求成功
$(document).ajaxComplete(function(){
//所有頁面中有很多個(gè)請求 這個(gè)回調(diào)就會(huì)至少多次
})
回到頂部
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)
}
});
移動(dòng)端點(diǎn)擊事件失效,iphonex的小條遮擋住底部的點(diǎn)擊事件
可以將click事件改為touchstart事件
touchstart事件:當(dāng)按下手指時(shí)觸發(fā)該事件
數(shù)組去重
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.將一個(gè)類數(shù)組對象或者可遍歷對象轉(zhuǎn)換成一個(gè)真正的數(shù)組,必須要有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相等,就表明是第一次出現(xiàn)
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四個(gè)單詞首字母大寫
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
關(guān)于瀏覽器的各種距離
瀏覽器可視區(qū)域的高度window.innerHeight
瀏覽器可視區(qū)域的寬度window.innerWidth
滾動(dòng)條滾動(dòng)的距離document.documentElement.scrollTop || document.body.scrollTop
元素距離頂部的高度offsetTop
元素距離左邊的距離offsetLeft
在ios或者某些華為機(jī)型中會(huì)出現(xiàn)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;//直接使用
}
手機(jī)號碼正則表達(dá)式
//第一位是【1】開頭,第二位則則有【3,4,5,7,8】,第三位則是【0-9】,第三位之后則是數(shù)字【0-9】。
let phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
//如果第二位改為了6啊 9什么的 就不驗(yàn)證第二位
var reg = /^1[0-9]{10}$/;
調(diào)整input框提示信息的樣式
input::-webkit-input-placeholder {
color: #FFB988;
font-size: 14px;
}
檢測用戶手機(jī)豎屏橫屏
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);
生成特定網(wǎng)站的二維碼
首先引入qrcode.js
var qrcode = new QRCode('qrcode', { // qrcode為id 頁面上需要有一個(gè)容器 id為qrcode來裝載這個(gè)二維碼
text: 'http://rbpicc.d.vipgogo.com/index/Notice/piccVip',
});
解決移動(dòng)端1px的渲染問題
在
Renita屏幕上,會(huì)將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只能點(diǎn)擊一次
//加一個(gè)這個(gè)class
.disable {
pointer-events: none;
}
函數(shù)節(jié)流
//比如 一個(gè)搜索框 用戶輸入需要一直
let timer;
$('.i1').bind('input propertychange', function(){
let value=$(this).val();
clearTimeout(timer);
timer = setTimeout(function() {
// 執(zhí)行具體代碼
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) {
// 正常方向或屏幕旋轉(zhuǎn)180度
console.log('豎屏');
};
if (window.orientation === 90 || window.orientation === -90 ){
// 屏幕順時(shí)鐘旋轉(zhuǎn)90度或屏幕逆時(shí)針旋轉(zhuǎn)90度
console.log('橫屏');
}
})
文本兩端對齊
<ul id="u1">
<li>姓名</li>
<li>手機(jī)號碼</li>
<li>賬號</li>
</ul>
#u1 li{
text-align: justify;
text-align-last:justify;
border: 1px solid red;
}

微信公眾號頁面播放音頻
因?yàn)樵趇os中 開始播放需要用點(diǎn)擊事件來觸發(fā)
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('上傳成功,再次點(diǎn)擊照片可更換照片');
$('.imgDiv').attr('isUpload','1')
}else{
toast(res.msg);
}
},
error:function (res) {
alert(JSON.stringify(res));
toast('系統(tǒng)錯(cuò)誤');
}
});
}
禁止微信分享
//禁止微信分享
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,當(dāng)然,瀏覽器自己肯定支持
// 指定格式PNG
image.src = canvas.toDataURL("image/png");
return image;
}
//獲取網(wǎng)頁中的canvas對象
var mycanvas1=document.getElementsByTagName('canvas')[0];
//將轉(zhuǎn)換后的img標(biāo)簽插入到html中
var img = convertCanvasToImage(mycanvas1);
$('#qrcode').append(img);//imgDiv表示你要插入的容器id
引入MUI的三級聯(lián)動(dòng)
<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上的參數(shù)
用的時(shí)候直接調(diào)用方法傳入?yún)?shù)就可以了
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);
}
取的參數(shù)中文會(huì)亂碼
decodeURI()
mui使用時(shí)間選擇器
mui.min.js mui.picker.min.js
mui.picker.min.css以及自己添加的樣式
/*mui 時(shí)間選擇器后加入的樣式*/
.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部分
//喚出時(shí)間選擇器
$('.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表單參數(shù)序列化
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;
}
安卓手機(jī)input框會(huì)擠壓視圖
let Height = $('body').height();
$(window).resize(function() {
$('body').height(Height);
});
--------------------------------------------------永久更新--------------------------------------------------------