BOM常用语法
- 浏览器尺寸
//可输入内容宽度(不含滚动条)
document.documentElement.clientWidth
//可输入内容宽度(含滚动条)
window.innerWidth
//浏览器窗口宽度 + 外面阴影的宽
window.outerWidth
//显示器的宽度
window.screen.width
//布局视口,不同设备都为980,主要为了兼容PC页面
document.documentElement.clientWidth
//视觉视口
window.innerWidth
//获取滚动条滚动距离
document.documentElement.scrollTop || document.body.scrollTop
- GET传参解析 根据URL的query返回对象形式
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
- 阻止页面内容被拷贝 - (相对)
<!--防止拷贝博文js代码-->
<script language="javascript">
function click() { return false; }
function click1() { if (event.button == 2) { return false; } }
function CtrlKeyDown() {
if (event.ctrlKey) { return false; }
}
if (window.Event) document.captureEvents(Event.MOUSEUP);
function nocontextmenu() {
event.cancelBubble = true event.returnValue = false;
return false;
}
function norightclick(e) {
if (window.Event) {
if (e.which == 2 || e.which == 3) return false;
} else {
if (event.button == 2 || event.button == 3) {
event.cancelBubble = true event.returnValue = false;
return false;
}
}
}
document.oncontextmenu = nocontextmenu; // for IE5+
document.onmousedown = norightclick; // for all others
document.onkeydown = CtrlKeyDown;
document.onselectstart = click;
document.onmousedown = click1;
document.oncontextmenu = function() {
return false;
};
//禁用开发者工具F12
document.onkeydown = function() {
if (window.event && window.event.keyCode == 123) {
event.keyCode = 0;
event.returnValue = false;
return false;
}
};
var element = new Image();
Object.defineProperty(element, 'id', {
get: function() {
/* TODO */
window.close();
window.location = "about:blank";
}
});
console.log('%cHello', element);
</script>
3-2. 阻止页面被嵌套iframe
try{
top.location.hostname;
if(top.location.hostname != window.location.hostname){
top.location.href =window.location.href;
}
}
catch(e){
top.location.href = window.location.href;
}
- 屏幕尺寸变化
orientationchange 事件在设备的纵横方向改变时触发
function resizeScreen(cbFn) {
if (window.addEventListener) {
if (window.orientation) {
window.addEventListener('orientationchange',
function() {
cbFn&& cbFn();
},
false);
} else {
window.addEventListener('resize',
function() {
cbFn&& cbFn();
},
false);
}
} else if (window.attachEvent) {
if (window.orientation) {
window.attachEvent('onorientationchange',
function() {
cbFn&& cbFn();
});
} else {
window.attachEvent('onresize',
function() {
cbFn&& cbFn();
});
}
}
}
4-2. 移动端旋转函数
- 如支持orientationchange事件,则通过window.orientation进行判断
- 不支持orientationchange事件,则通过屏幕宽高长短进行判断
- 最终在html标签上添加类名landscape或portrait来进行样式修改
var supportOrientation = (typeof window.orientation === 'number' && typeof window.onorientationchange === 'object');
var orientationInitFn = function(){
var htmlNode = document.body.parentNode,orientation;
var updateOrientation = function(){
if(supportOrientation){
orientation = window.orientation;
switch(orientation){
case 90:
case -90:
orientation = 'landscape';
break;
default:
orientation = 'portrait';
break;
}
}else{
orientation = (window.innerWidth > window.innerHeight) ? 'landscape' : 'portrait';
}
htmlNode.setAttribute('class',orientation);
};
if(supportOrientation){
window.addEventListener('orientationchange',updateOrientation,false);
}else{
//监听resize事件
window.addEventListener('resize',updateOrientation,false);
};
updateOrientation();
};
window.addEventListener('DOMContentLoaded',orientationInitFn,false);
4-3. 判断手机正放、倒立、还是横向 - 来自MDN
var orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;
if (orientation === "landscape-primary") {
console.log("That looks good.");
} else if (orientation === "landscape-secondary") {
console.log("Mmmh... the screen is upside down!");
} else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
console.log("Mmmh... you should rotate your device to landscape");
} else if (orientation === undefined) {
console.log("The orientation API isn't supported in this browser :(");
};
- 一个全端吸顶导航的思路 (内容上滑导航隐藏,内容下滑导航显示)
在不使用触摸事件的情况下,如何判断移动端、PC端,页面滚动的方向
- 主要通过scrollTop的前后比对,借助JQuery的库方便些
- 因为涉及到监测scroll事件,所以还需要做下防抖的工作
- 在IOS端,由于页面本身存在弹性滚动的浏览器默认渲染问题,所以需要修正下BUG
- 当scrollTop小于屏幕高度一半时候,不再做隐藏导航的操作,由于上面3
//判断全端滚动方向
var scrollWinPoints = [];
var scrollWin = $(window);
scrollWin.bind('scroll',function(e){
scrollWinPoints.push(scrollWin.scrollTop());
clearTimeout(scrollWin.iTimer);
scrollWin.iTimer = setTimeout(function(){
if(scrollWinPoints.length>=2){
if(scrollWinPoints[scrollWinPoints.length-1]>scrollWinPoints[0]){
// console.log('向下');
//IOS 弹性滚动默认行为导致的问题
if(scrollWin.scrollTop()<scrollWin.height()/2){
return false;
}else{
//隐藏导航
if(!searchToolBox.hasClass('hideSearchToolBox')){
searchToolBox.addClass('hideSearchToolBox');
};
}
}else{
// console.log('向上');
//显示导航
searchToolBox.removeClass('hideSearchToolBox');
}
scrollWinPoints = [];
};
},200);
});
- chrome 浏览器截图功能
- 按F12,打开开发者工具
- 按ctrl+shift+p 或者 点击开发者工具中,右上角三个点,小燕子 Run command ( Ctrl+Shift+P )
-
输入cap关键字,可以选择四种截图( Screenshot )方式
截屏菜单
- 可以选择 全屏Capture full size screenshot
- 如果选择 Capture node screenshot 截屏某个node节点,需要提前在开发者工具的Elements的某个node提前选中
- 关于资源预加载
link标签,可以通过设置rel、as相关属性来进行资源预加载,具体操作
<link rel="preload" href="./manifest.js" as="script">
<link rel="preload" href="./welcome.mp3" as="audio">
<link rel="preload" href="./welcome.mp4" as="video">
<link rel="preload" href="./icon.jpg" as="image">
<link rel="preload" href="./xxx.woff" as="font">
...
注意:
- 预加载资源不会即可生效,只有使用时候才会渲染
- rel属性有两个预加载值,preload-针对当前页面资源,prefetch-针对可能跳转页面的资源
- preload与prefetch不能针对同一个资源一起使用,否则会加载两次
- preload 不会阻塞 windows 的 onload 事件,对跨域的文件进行preload时,必须加上 crossorigin 属性
- as为必填属性,不带 “as” 属性的 preload 的优先级将会等同于异步请求
- link标签支持onload事件,可以针对资源加载后做对应的逻辑处理
<link rel="preload" href="..." as="..." onload="preloadFinished()">
- link标签支持媒体查询,可以针对不同屏幕,定制化去加载资源,如图片
<link rel="preload" href="aaa.jpg" as="image" media="(max-width: 640px)">
<link rel="preload" href="bbb.jpg" as="image" media="(min-width: 641px)">
终端判断
- 通过特定行为判断,如:
是否存在点触事件
function isNotpc() {
return ('ontouchstart' in document.documentElement);
};
是否可以旋转屏幕
if (typeof window.orientation !== 'undefined') {
// 当前设备是移动设备
};
- 通过userAgent来做关键词解析,绝大部分网站使用该方式:
※ 完美世界
function isMobile(){
var userAgentInfo = navigator.userAgent;
var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod", "Windows CE", "BlackBerry");
var flag = false;
for (var v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = true; break; }
}
return flag;
}
※ 网络来源
声明:
var browser = {
versions: function() {
var u = navigator.userAgent,
app = navigator.appVersion;
return {
trident: u.indexOf('Trident') > -1,
//IE内核
presto: u.indexOf('Presto') > -1,
//opera内核
webKit: u.indexOf('AppleWebKit') > -1,
//苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
//火狐内核
mobile: !!u.match(/AppleWebKit.*Mobile.*/),
//是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
//ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1,
//android终端
iPhone: u.indexOf('iPhone') > -1,
//是否为iPhone或者QQHD浏览器
iPad: u.indexOf('iPad') > -1,
//是否iPad
Safari: u.indexOf('Safari') > -1,
//是否Safari
weixin: u.indexOf('MicroMessenger') > -1,
//是否微信 (2015-01-22新增)
qq: u.match(/\sQQ/i) == " qq" //是否QQ
};
} (),
language: (navigator.browserLanguage || navigator.language).toLowerCase()
}
调用
if (browser.versions.mobile) {
if (browser.versions.android) {
console.log('android');
} else if (browser.versions.iPhone) {
console.log('iPhone');
}
} else {
//pc端不做操作
}
※ 360路由
var common = {};
common.ua = navigator.userAgent;
common.iphone = common.ua.indexOf('iPhone;') >= 0;
common.ipad = common.ua.indexOf('iPad;') >= 0;
common.ipod = common.ua.indexOf('iPod;') >= 0;
common.android = common.ua.indexOf(' Android') >= 0;
common.mobile = !!common.ua.match(/AppleWebKit.*Mobile.*/);
common.winPhone= common.ua.indexOf('Windows Phone') >= 0;
if (common.iphone || common.ipad || common.ipod || common.android || common.mobile || common.winPhone) {
window.location.href = "/mobile/index.html";
$.cookie("from","index",{ path: '/', expires: 1 });
} else {
window.location.href = "/login_pc.htm";
}
※ Bilibili
//判断终端是否为移动端
!function(){
var i=window.navigator.userAgent,n=["Android","iPhone","SymbianOS","Windows Phone","iPod"],o=!0;
if(!/\sVR\s/g.test(i)){
for(var e=0,r=n.length;e<r;e++)if(0<i.indexOf(n[e])){o=!1;break}if(!o){
var a=window.location.href.replace("www","m");
window.location.href=a
}
}
}();
判断浏览器特定版本,做兼容使用
如:低版本IE跳转
※ B站来源
//判断IE版本
function getIEVersion(){
var e=99;if("Microsoft Internet Explorer"==navigator.appName){var t=navigator.userAgent;null!=new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})").exec(t)&&(e=parseFloat(RegExp.$1))}return e
};
//判断并进行跳转
getIEVersion()<11 && (window.location.href="https://www.bilibili.com/blackboard/activity-I7btnS22Z.html");
![](https://img.haomeiwen.com/i13748290/5f9c32bafbf05319.png)
※ 判断是否为IE
function isIE(){
if(!!window.ActiveXObject || "ActiveXObject" in window){
return true;
}else{
return false;
}
}
※ 判断IE版本,返回数字
function IEVersion() {
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;
if(isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
if(fIEVersion == 7) {
return 7;
} else if(fIEVersion == 8) {
return 8;
} else if(fIEVersion == 9) {
return 9;
} else if(fIEVersion == 10) {
return 10;
} else {
return 6;//IE版本<=7
}
} else if(isEdge) {
return 'edge';//edge
} else if(isIE11) {
return 11; //IE11
}else{
return -1;//不是ie浏览器
}
}
※ 判断是否IE8以下
var isIE8 = !+"\v1";
console.log(isIE8);
※ 判断浏览器版本
function browserVersion() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //Edge浏览器
var isFirefox = userAgent.indexOf("Firefox") > -1; //Firefox浏览器
var isOpera = userAgent.indexOf("Opera")>-1 || userAgent.indexOf("OPR")>-1 ; //Opera浏览器
var isChrome = userAgent.indexOf("Chrome")>-1 && userAgent.indexOf("Safari")>-1 && userAgent.indexOf("Edge")==-1 && userAgent.indexOf("OPR")==-1; //Chrome浏览器
var isSafari = userAgent.indexOf("Safari")>-1 && userAgent.indexOf("Chrome")==-1 && userAgent.indexOf("Edge")==-1 && userAgent.indexOf("OPR")==-1; //Safari浏览器
if(isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
if(fIEVersion == 7) {
return 'IE7';
} else if(fIEVersion == 8) {
return 'IE8';
} else if(fIEVersion == 9) {
return 'IE9';
} else if(fIEVersion == 10) {
return 'IE10';
} else {
return 'IE6';//IE版本<7
}
} else if(isIE11) {
return 'IE11';
} else if(isEdge) {
return 'Edge'+userAgent.split('Edge/')[1].split('.')[0];
} else if(isFirefox) {
return 'Firefox'+userAgent.split('Firefox/')[1].split('.')[0];
} else if(isOpera) {
return 'Opera'+userAgent.split('OPR/')[1].split('.')[0];
} else if(isChrome) {
return 'Chrome'+userAgent.split('Chrome/')[1].split('.')[0];
} else if(isSafari) {
return 'Safari';+userAgent.split('Safari/')[1].split('.')[0];
} else{
return -1;//不是ie浏览器
}
}
浏览器常见问题
- IE浏览器不支持直接修改图片格式的图片,会报错
无法解码 URL 处的图像:“https://www.xxx.com/temp/a0a4fc59b82a.JPG”。
- 解决方式:
不简单粗暴的修改后缀名,而是通过图片处理工具来修改图片
其他浏览器功能语法
- 图片本地预览
//-- html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<style type="text/css">#preview, .img, img { width:200px; height:200px; } #preview { border:1px solid #000; }</style></head>
<body>
<div id="preview"></div>
<input type="file" onchange="preview(this)" />
</body>
</html>
//-- js
<script type="text/javascript">
function preview(file) {
var prevDiv = document.getElementById('preview');
if (file.files && file.files[0]) {
var reader = new FileReader();
reader.onload = function(evt) {
prevDiv.innerHTML = '<img src="' + evt.target.result + '" />';
}
reader.readAsDataURL(file.files[0]);
} else {
prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
}
}
</script>
未完待续...
网友评论