js获取screen信息、cookie和query参数格式化
前言
js实现获取screen信息和query参数格式化、获取cookie
一、获取screen信息
function getScreenInfo() {
try {
var screenTop = (win.mozInnerScreenY || win.screenTop);
var screenLeft = (win.mozInnerScreenX || win.screenLeft);
if (typeof screenTop === 'undefined') {
screenTop = 0;
}
if (typeof screenLeft === 'undefined') {
screenLeft = 0;
}
// 网页可见区域 浏览器窗口可视区域大小(不包括工具栏和滚动条等边线)
var clientWidth = document.documentumentElement.clientWidth || document.body.clientWidth;
var clientHeight = document.documentumentElement.clientHeight || document.body.clientHeight;
// 屏幕分辨率
var screenWidth = win.screen.width;
var screenHeight = win.screen.height;
// 屏幕可用工作区
var availWidth = win.screen.availWidth;
var availHeight = win.screen.availHeight;
// 外部高度
var outerWidth = win.outerWidth;
var outerHeight = win.outerHeight;
// 文档高度 网页内容实际宽高(包括工具栏和滚动条等边线)
var scrollWidth = document.documentumentElement.scrollWidth || document.body.scrollWidth;
var scrollHeight = document.documentumentElement.scrollWidth || document.body.scrollHeight;
return {
'screenTop': screenTop,
'screenLeft': screenLeft,
'clientWidth': clientWidth,
'clientHeight': clientHeight,
'screenWidth': screenWidth,
'screenHeight': screenHeight,
'availWidth': availWidth,
'availHeight': availHeight,
'outerWidth': outerWidth,
'outerHeight': outerHeight,
'scrollWidth': scrollWidth,
'scrollHeight': scrollHeight
};
}
catch (err) {
// catch
}
}
二、query参数格式化
代码如下(示例):
function getUrlQueryObj(url) {
const arrList = decodeURIComponent(url).split('?');
const queryObj = {
};
let arr = null;
for (let i = 1, len = arrList.length; i < len; i++) {
const query = arrList[i];
const queryArr = query.split('&');
for (const item of queryArr) {
arr = item.split('=');
arr[1] && (queryObj[arr[0]] = arr[1]);
if (arr[1] && arr[1].indexOf('#/') !== -1) {
queryObj[arr[0]] = arr[1].split('#/')[0];
}
}
}
return queryObj;
};
三、获取cookie
代码如下(示例):
// 第一种
function getCookie(name) {
var arr;
var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
if (arr = document.cookie.match(reg)) {
return decodeURI(arr[2]);
} else {
return null;
}
}
// 第二种
function getCookie(name) {
var prefix = name + "="
var start = document.cookie.indexOf(prefix)
if (start == -1) {
return null;
}
var end = document.cookie.indexOf(";", start + prefix.length)
if (end == -1) {
end = document.cookie.length;
}
var value = document.cookie.substring(start + prefix.length, end)
return unescape(value);
}
四、获取安卓版本号
function get_android_version() {
var ua = navigator.userAgent.toLowerCase();
var version = null;
if (ua.indexOf('android') > 0) {
var reg = /android [._]+/gi;
var vInfo = ua.match(reg);
version = (vInfo + '').replace(/[^0-9|_.]/ig, '').replace(/_/ig, '.'); // 得到版本号4.2.2
version = parseInt(version.split('.')[0], 10);// 得到版本号第一位
}
return version;
}