本篇文章总结了一些自己在移动端页面开发中经常用到的utils,总结出来仅供参考,后会持续更新。。。
禁止右键点击
/* 禁止右键,复制与选择文本 */
/**
* [disabledKeys 禁止右键,复制与选择文本]
* @return {[type]} [description]
*/
export const disabledKeys = () => {
document.body.oncontextmenu = document.body.ondragstart = document.body.onbeforecopy = () => {
return false
}
const doKey = (e) => {
var ev = e || window.event // 获取event对象
var obj = ev.target || ev.srcElement // 获取事件源
var t = obj.type || obj.getAttribute('type') // 获取事件源类型
if (ev.keyCode === 8 && t !== 'password' && t !== 'text' && t !== 'textarea' && t !== 'tel') {
return false
}
if (!(ev.keyCode === 86 && ev.ctrlKey) && !(ev.keyCode === 67 && ev.ctrlKey) && (ev.ctrlKey || ev.keyCode == 78 && ev.ctrlKey || ev.altKey || ev.altKey && ev.keyCode == 115)) {
return false
}
}
// 禁止后退等其它按键 作用于Firefox、Opera
document.onkeypress = doKey
// 禁止后退等其它按键 作用于IE、Chrome
document.onkeydown = doKey
}
解析url中param为json
/**
* [getUrlParam 解析url参数]
* @param {[type]} url [url地址]
* @param {[type]} name [参数的key]
* @return {[type]} [参数的值]
*/
export const getUrlParam = function (url = location.href, name) {
var pattern = new RegExp('[?&]' + name + '\=([^&]+)', 'g')
var matcher = pattern.exec(url)
var items = null
if (matcher !== null) {
try {
items = decodeURIComponent(decodeURIComponent(matcher[1]))
} catch (e) {
try {
items = decodeURIComponent(matcher[1])
} catch (e) {
items = matcher[1]
}
}
}
return items
}
日期格式化
/**
* [dateFormat 日期格式化]
* @param {[type]} date [description]
* @param {String} format [description]
* @return {[type]} [description]
*/
export const dateFormat = function (date, format = 'yyyy-MM-dd') {
var o = {
'M+': date.getMonth() + 1, // 月
'd+': date.getDate(), // 日
'h+': date.getHours(), // 时
'm+': date.getMinutes(), // 分
's+': date.getSeconds() // 秒
}
if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
for (var k in o) { if (new RegExp('(' + k + ')').test(format)) format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) }
return format
}
函数去抖
/**
* 函数去抖动
* @param {*} func
* @param {*} delay
*/
export const debounce = (func, delay) => {
let timer = null
return () => {
const context = this
const args = arguments
clearTimeout(timer)
timer = setTimeout(() => {
func.apply(context, args)
}, delay)
}
}
数组检测方法兼容
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]'
}
}
检测网络是否正常
// 检测网络是否正常
const updateOnlineStatus = (event) => {
let onLine = navigator.onLine
console.log('network', onLine)
}
window.addEventListener('online', updateOnlineStatus)
window.addEventListener('offline', updateOnlineStatus)
横竖屏判断
/**
* 判断当前横竖屏
*/
const detectOrient = (verticalCb = () => {}, crossCb = () => {}) => {
// 不一定要使用localStorage,其他存储数据的手段都可以
const storage = localStorage
let data = storage.getItem('J-recordOrientX')
let cw = document.documentElement.clientWidth
let _Width = 0
let _Height = 0
if (!data) {
let sw = window.screen.width
let sh = window.screen.height
// 2.在某些机型(如华为P9)下出现 srceen.width/height 值交换,所以进行大小值比较判断
_Width = sw < sh ? sw : sh
_Height = sw >= sh ? sw : sh
storage.setItem('J-recordOrientX', _Width + ',' + _Height)
} else {
let str = data.split(',')
_Width = str[0]
_Height = str[1]
}
if (cw === _Width) {
verticalCb()
// 竖屏
return
}
if (cw === _Height) {
crossCb()
// 横屏
}
}
移动端使用rem适配
(function () {
var docEl = document.documentElement;
var width = document.documentElement.clientWidth || document.body.clientWidth;
var rem = width / 10;
docEl.style.fontSize = rem + 'px';
function repairFontSize() {
var testDiv = document.createElement('div');
testDiv.style.width = '10rem';
testDiv.style.position = 'absolute';
testDiv.style.left = '0';
testDiv.style.right = '0';
testDiv.style.visibility = 'hidden';
testDiv.style.zIndex = '10';
document.body.appendChild(testDiv);
var rect = testDiv.getBoundingClientRect();
var scaleRatio = rect.width / width;
//兼容某些安卓机型尺寸不是10rem
if (scaleRatio !== 1) {
console.log('Page scale ratio detected. ' + scaleRatio);
docEl.style.fontSize = rem / scaleRatio + 'px';
}
document.body.removeChild(testDiv);
document.removeEventListener('DOMContentLoaded', repairFontSize);
}
document.addEventListener('DOMContentLoaded', repairFontSize);
document.addEventListener('load', repairFontSize);
}());
手机类型判断
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
window.isMobile= true;
alert("true");
} else {
window.isMobile= false;
}
判断设备类型
let isWebkit = /Webkit/i.test(navigator.userAgent),
let isChrome = /Chrome/i.test(navigator.userAgent),
let isMobile = !!("ontouchstart" in window),
let isAndroid = /Android/i.test(navigator.userAgent),
let isIE = document.documentMode;
支付宝账号
if(/^0?(13[0-9]|15[012356789]|18[0123456789]|14[0123456789]|17[0123456789])[0-9]{8}$/.test(exampleInputOrder.value)){
console.log("支付宝账号正确!")
} else if(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(exampleInputOrder.value)){
console.log("支付宝账号正确!")
} else {
console.log("请输入您的支付宝账号!")
return;
}
JS获取经纬度
functionjwdPos(){
navigator.geolocation.getCurrentPosition(
(pos)=>{
var jingdu=pos.coords.latitude;
var weidu=pos.coords.longitude;
alert(weidu);
}
);
}
判断浏览器是否加载flash
//判断是否加载flash
function flashChecker() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
var hasFlash = 0; //是否安装了flash
var flashVersion = 0; //flash版本
if (isIE||isEdge||isIE11) {
var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (swf) {
hasFlash = 1;
VSwf = swf.GetVariable("$version");
flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
}
} else {
if (navigator.plugins && navigator.plugins.length > 0) {
var swf = navigator.plugins["Shockwave Flash"];
if (swf) {
hasFlash = 1;
var words = swf.description.split(" ");
for (var i = 0; i < words.length; ++i) {
if (isNaN(parseInt(words[i]))) continue;
flashVersion = parseInt(words[i]);
}
}
}
}
return { f: hasFlash, v: flashVersion };
}
var fls = flashChecker();
if (!fls.f) alert("您没有安装flash,请确认安装最新版本的flash插件,否则网页无法正常显示");