1. 加入收藏夹代码



<script type="text/javascript">
function AddFavorite(sURL,sTitle){
try{
window.external.addFavorite(sURL, sTitle);
}catch (e){
try{
window.sidebar.addPanel(sTitle, sURL, "");
}catch (e){
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
}
}
</script>
<a href=”javascript:favorite(‘李刚的学习专栏

2. 设置给任何层添加事件触发调用对象层的内容



function showid(idname){
var newBox=document.getElementById(idname);
console.log(newBox)
}
//调用方法:
<a href="#none" onClick="showid('box')">测试按钮</a>
<div id="box">测试内容</div>

3. js 获取文档高度


网页可见区域宽:document.body.clientWidth

网页可见区域高:document.body.clientHeight

网页可见区域宽:document.body.offsetWidth (包括边线的宽)

网页可见区域高:document.body.offsetHeight (包括边线的宽)

网页正文全文宽:document.body.scrollWidth

网页正文全文高:document.body.scrollHeight

网页被卷去的高:document.body.scrollTop

网页被卷去的左:document.body.scrollLeft

网页正文部分上:window.screenTop

网页正文部分左:window.screenLeft

屏幕分辨率的高:window.screen.height

屏幕分辨率的宽:window.screen.width

屏幕可用工作区高度:window.screen.availHeight

屏幕可用工作区宽度:window.screen.availWidth

HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth

scrollHeight: 获取对象的滚动高度。

scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离

scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离

scrollWidth:获取对象的滚动宽度

offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度

offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置

offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置

event.clientX 相对文档的水平座标

event.clientY 相对文档的垂直座标

event.offsetX 相对容器的水平坐标

event.offsetY 相对容器的垂直坐标

document.documentElement.scrollTop 垂直方向滚动的值

event.clientX+document.documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量


4. js获取对象字符串,截取所需位数的内容



var data = $('a').text();
data = data.length > 20 ? (data.substring(0,20)+"…") : data;

5. Javascript获取地址栏参数的三种方法



//方法一:
<script type="text/javascript">
String.prototype.getQuery = function(name) {
var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
var r = this.substr(this.indexOf("\?")+1).match(reg);
if (r!=null)
return unescape(r[2]);
return null;
}
var strHref = "www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc";
console.log(strHref.getQuery("a"));
console.log(strHref.getQuery("b"));
console.log(strHref.getQuery("c"));
</script>
//方法二:
<script type="text/javascript">
function getUrlPara(paraName){
var sUrl = location.href;
var sReg = "(?:\\?|&){1}"+paraName+"=([^&]*)";
var re=new RegExp(sReg,"gi");
re.exec(sUrl);
return RegExp.$1;
}
//应用实例:test_para.html?a=11&b=22&c=33
console.log(getUrlPara("a"));
console.log(getUrlPara("b"));
</script>
//方法三:
<script type="text/javascript">
function Request(strName){
var strHref = "www.cnlei.org/index.htm?a=aaa&b=bbb&c=ccc";
var intPos = strHref.indexOf("?");
var strRight = strHref.substr(intPos + 1);
var arrTmp = strRight.split("&");
for(var i = 0; i < arrTmp.length; i++) {
var arrTemp = arrTmp[i].split("=");
if(arrTemp[0].toUpperCase() == strName.toUpperCase())
return arrTemp[1];
}
return "";
}
console.log(Request("a"));
console.log(Request("b"));
console.log(Request("c"));
</script>

6. div已经有一个class值,s再给它添加一个class值



document.getElementById("comn").className+=" comn";

7. iframe操作


a. 在iframe子页面中获取当前iframe的id(firefox可以)

var frameId = window.frameElement && window.frameElement.id || '';

遍历父页面所有iframe并输出ID(firefox可以)


function iframeID(){
var fs = window.parent.window.frames;
for(var i = 0; i < fs.length; i++){
if (window == fs[i]){
console.log(window.parent.document.getElementsByTagName("iframe")[i].id)
return window.parent.document.getElementsByTagName("iframe")[i].id;
}
}
};

b. js判断iframe是否加载完成


var iframe = document.createElement("iframe");
iframe.src = "http://www.planabc.net";
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
alert("Local iframe is now loaded.");
});
} else {
iframe.onload = function(){
alert("Local iframe is now loaded.");
};
}

c. js判断iframe是加载成功还是加载失败


url = document.getElementById('iframe1').src;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",url,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
alert("加载成功!");
} else {
alert("加载失败!");
}
}
}
var oFrm = document.getElementById("ifrm");
oFrm.onload = oFrm.onreadystatechange = function() {
if (this.readyState && this.readyState != 'complete')
return;
else {
onComplete();
}
}

d 加载iframe 禁用缓存


1. 将http header访问设置成no-cache的:


<meta HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<meta HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">

2. 在web site 后面加个随机参数,绕过相同url读取cache问题


iframeObj.src = "http://www.example.com/page/myframe.html?random=" + (new Date()).getTime() + Math.floor(Math.random() * 1000000);

8. 验证邮箱格式是否正确



function chkEmail(strEmail) {
if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(strEmail)) {
return false;
}
else {
return true;
}
}

9. 判断设备为PC或是移动终端



//判断平台
isPCByPlat = function(){
var platForm = navigator.platform.toLowerCase();
var isWin = (platForm=="win32")||(platForm=="win64")||(platForm=="windows")||(platForm.indexOf("win") > -1);
if(isWin)
return "windows";
var isMac = (platForm=="mac68k")||(platForm=="macppc")||(platForm=="macintosh")||(platForm=="macintel");
if(isMac)
return "mac";
return false;
};
//判断UA
isPCByOSList = function(uaArg){
var pcOS = ["AIX","Amiga","BeOS","DragonFly","FreeBSD","GNU","Haiku","HP-UX","IRIX","Joli","Java","Macintosh","Minix","MorphOS","NetBSD","OpenBSD","PClinuxOS","QNX x86pc","SunOS","Ubuntu","Mint","Red Hat","Slackware","SUSE","PCLinuxOS","Debian","Fedora","CentOS","Vine","Arch Linux","Gentoo","Kanotix","Mandriva"];
for (var i = 0; i < pcOS.length; i++){
if(uaArg.indexOf(pcOS[i]) > -1){
return true;
}
};
return false;
};

if(isPCByPlat() || isPCByOSList(navigator.userAgent)){
console.log("PC");
} else {
console.log("Mobile");
};

10. 动态插入js



function loadScript(url, callback) {
//创建script
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
//加载完毕回调
if(script.readyState) { //for IE
script.onreadystatechange = function() {
if(script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
if(callback){
callback();
}
}
};
}else { //for Others
script.onload = function() {
if(callback){callback();}
};
}
}
//加载script
loadScript("http://www.ueder.net/testhtml/jquery/jquery.js");

11. js实现页面跳转的几种方式


a. window.location.href="login.jsp?backurl="+window.location.href;

b. window.history.back(-1); //返回

c. window.navigate("top.jsp"); //针对IE的

d. self.location="top.htm";

e. top.location="xx.jsp"; //非法访问


12. js获取css属性值



/**
* GetCurrentStyle
*/
function GetCurrentStyle(obj, style){
if (obj.currentStyle) { //IE浏览器
return obj.currentStyle[style];
} else if (window.getComputedStyle) { //W3C标准浏览器
propprop = style.replace(/([A-Z])/g, "-$1");
propprop = style.toLowerCase();
return document.defaultView.getComputedStyle(obj, null)[propprop];
}
return null;
}; //GetCurrentStyle


var dd = document.getElementById("box");
console.log(GetCurrentStyle(dd, "display"));

13. 日期转数值



var d = +new Date();

14. 漂亮的随机码



Math.random().toString(16).substring(2); //14位
Math.random().toString(36).substring(2); //11位

15. 用0补全位数



function prefixInteger(num, length) {
return (num / Math.pow(10, length)).toFixed(length).substr(2);
};
prefixInteger(31, 4);//0031