js 积累

获取元素方式

oDiv.style.width = '12px';
oDiv.style['width'] = '12px';
oDiv.getAttribute('width')   // oDiv.setAttribute('width', '120px'), removeAttribute('width')
// 能用 . 的地方都能用 ['width'] ,反之不行。 

css 怎么用,js 里也怎么用,除了 className

oDiv.style.width = '12px';  // div{ width:12px; }

oDiv.style.className= 'nav';  // div.nav{ ... }

onclick 等其实也是元素的属性

<input type="text" id="input1" />
<script>
    var input1 = document.getElementById('input1');
    input1.onclick = function(){ return true; }
</script>

自定义属性要加在 js 内,不要加载 html 中

<input type="text" id="input1" index=1 />

<script>
var input1 = document.getElementById('input1');
input1.index = 1;
</script>

html、css、js 应当三者分离编码

设置 checkbox 的属性

var checkbox1 = document.getElementById('checkbox1');
checkbox1.checked = true;

变量类型

string、number、boolean、array、object、null、undefined
未声明的变量为 undefined :typeof b;
未赋值的已声明变量 undefined: var c;typeof c;
(获取的元素不存在)的类型还是 object,只是该对象的值为 null:var a=document.getElementById('a'); alert(typeof a);
number:typeof(parseInt('a'));

数组和 json

var student = {
    "name":"Bill Gates",
    "street":"Fifth Avenue New York 666",
    "age":56,
    "phone":"555 1234567"
};
alert(student.name);
alert(student['name']); // 能用 . 的地方都能用 [''] ,反之不行。 

区别
1. 数组通过数字下标获取元素的值,而 json 通过字符串下标获取。
2. json 没有 length。
3. 循环 : 数组尽量使用 for(),json 只能用 for in

获取样式

function getStyle(obj,name){
    if(obj.currentStyle){
        return obj.currentStyle[name];
    }else{
        return getComputedStyle(obj,false)[name];
    }
}
// 注意复合样式的时候 传 name 不能只是传 background ,需要传入 backgroundColor,设置的时候无所谓了。

数组操作

arr.length = 0;   // 清空数组
arr.push(10);
arr.pop();
arr.shift(1);
arr.unshift();
arr.splice(2,2);
arr.splice(2,2,'a','b');   // 从下表为 2 的开始,替换 2 个 为后面几个参数 'a','b'
arr1.concat(arr2);
arr.join('-');      // 数组内元素通过字符串链接
arr.sort();
arr.sort(function(n1,n2){ return n1-n2; });

获取字符串第三位 请使用 str.charAt(2) , 使用 str[2] 会有兼容性问题

DOM 基础

childNodes 有的浏览器会包含文本节点。所以使用 nodeType ,其值为3是文本节点,值为1是元素节点。

for(var $i=0; $i<oUl.childNodes.length; $i++){
    if(oUl.childNodes[$i].nodeType == 1){
        oUl.childNodes[$i].style.background = 'red';
    }
}
children 可以兼容所有浏览器并且不会把文本节点包含进去。
parentNode  父节点   offsetParent 相对位置父节点
首节点:firstChild    firstElementChild
尾节点:lastChild     lastElementChild
兄弟节点:nextSibling     nextElementSibling
        previousSibling     previousElementSibling

getByClass

function getByClass(oParent, sClass){
    var aResult = [];
    var aEle = oParent.getElementsByTagName(*);
    for(var $i=0; $i<aEle.length; $i++){
        if(aEle[i].className == sClass){
            aResult.push(aEle[i]);
        }
    }
    return aResult;
}

任何标签都可以加ID,包括link。任何标签的任何属性,也都可以修改。

this 指代发生事件的元素,不要想当然。例如:点击按钮,this 指代的是按钮,并不是你想操作的那个元素。

两种情况发生隐式转化:判断表达式,加减。

时间函数

年 getFullYear() 月 getMonth() 日 getDate() 日 getDay()

DOM

childNodes       nodeType          children
parentNode       offsetParent
firstChild       firstElementChild
lastChild        lastElementChild
nextSibling      nextElementSibling
previousSibling  previousElementSibling
getAttribute     setAttribute     removeAttribute

DOM

createElement appendChild

insertBefore removeChild

document.createDocumentFragment()

// 直接 insertBefore 可能不兼容
if(aLi.length>0){
  oUl.insertBefore(oLi, aLi[0]);
}else{
  oUl.appendChild(oLi);
}
var oFrag=document.createDocumentFragment();
for (var i=0;i<10000;i++) {
  var oLi=document.createElement('li');
  oFrag.appendChild(oLi);
}

表格

tBodies、tHead、tFoot、rows、cells

表单

onsubmit

onreset

onkeyup

onblur

运动

开定时器前,不管存不存在定时器。先关一下,否则在重复点击按钮的时候,会形成多个定时器,导致移动速度过快。

在定时器开启后,需要用 if else 将 关闭定时器和 移动代码 分隔开,否则点击移动按钮,即使到了重点,依然会移动一次。

var timer=null;

function startMove()
{
    var oDiv=document.getElementById('div1');

    clearInterval(timer);
    timer=setInterval(function (){
        var speed=1;

        if(oDiv.offsetLeft>=300)
        {
            clearInterval(timer);
        }
        else
        {
            oDiv.style.left=oDiv.offsetLeft+speed+'px';
        }
    }, 30);
}

BOM

window.close 关闭时提示问题。可以用 open 打开,再去调用 close,这样就不会阻止代码关闭窗口了。

var oNewWin=window.open('about:blank', '_blank');
oNewWin.document.write(oTxt.value);

window.open() - 打开新窗口
window.close() - 关闭当前窗口
window.moveTo() - 移动当前窗口
window.resizeTo() - 调整当前窗口的尺寸

alert(window.navigator.userAgent);
// 警告:来自 navigator 对象的信息具有误导性,不应该被用于检测浏览器版本,这是因为:1. navigator 数据可浏览器无法报告晚于浏览器发布的新操作系统。 2. 被浏览器使用者更改


alert(window.location);
window.location='http://www.z.com/';

window.onload
window.onunload

// 可视区
alert('宽:'+document.documentElement.clientWidth+'高:'+document.documentElement.clientHeight);

// 滚动区
//IE、FF
//alert(document.documentElement.scrollTop);
//chrome
//alert(document.body.scrollTop);
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;

confirm    // 返回 boolean,要么 true,要么 false
prompt     // 取消返回 null (null 的类型是 object),其余返回都是 string,包括空字符串
var oDate=new Date();
oDate.setDate(oDate.getDate()+14);
document.cookie='user=blue;expires='+oDate;
alert(document.cookie);

封装 cookie

function setCookie(name, value, iDay){
    var oDate=new Date();
    oDate.setDate(oDate.getDate()+iDay);
    document.cookie=name+'='+value+';expires='+oDate;
}

function getCookie(name){
    var arr=document.cookie.split('; ');    
    for(var i=0;i<arr.length;i++){
        var arr2=arr[i].split('=');
        if(arr2[0]==name){
            return arr2[1];
        }
    }
    return '';
}

function removeCookie(name){
    setCookie(name, 1, -1);
}

setCookie('userName', 'dancingblue', 365);
setCookie('password', '123456', 14);
removeCookie('password');
alert(document.cookie);

字符串操作

// alert(str.substring(2, 5));  //不包括结束位置

正则

var re=/a/i;
var str='abcdef';
alert(str.search(re));      // 0

var str='adsf 03 23 vcxzxcv';
var re=/\d/;    
alert(str.search(re));      // 5

var str='asdf 34 656 cvs33';
var re=/\d/g;
alert(str.match(re));       // [3,4,6,5,6,3,3]

var str='asdf 34 656 cvs33';
var re=/\d+/g;
alert(str.match(re));       // [34,656,33]

var str='abc aaa erw';
var re=/a/g;
alert(str.replace(re, '0'));  // 0bc 000 erw

var re=/<[^<>]+>/g;
oTxt2.value=oTxt1.value.replace(re, ''); // 过滤尖括号

var re=new RegExp('b', 'i');   // 另一种正则表达式
var str='abcdef';
alert(str.search(re))

面向对象

function show() {
    alert(this);
}
show();         // object window
new show();     // object Object
// 为了使 对象 共用 方法 prototype
function CreatePerson(name, qq){     //构造函数
    this.name=name;
    this.qq=qq;
}

CreatePerson.prototype.showName=function (){    //原型
    alert('我的名字叫:'+this.name);
};

CreatePerson.prototype.showQQ=function (){
    alert('我的QQ号:'+this.qq);
};

var obj=new CreatePerson('blue', '258248832');
var obj2=new CreatePerson('张三', '45648979879');

obj.showName();
obj.showQQ();
obj2.showName();
obj2.showQQ();
alert(obj.showName==obj2.showName);

命名空间

// 命名空间
// json 可以存储任意类型,函数恰好也是 js 中的类型。
var zns={};

zns.common={};
zns.fx={};
zns.site={};

zns.common.getUser=function ()
{
    alert('a');
};

zns.fx.getUser=function ()
{
    alert('b');
};

zns.site.getUser=function ()
{
    alert('c');
};

zns.common.getUser();
zns.fx.getUser();
zns.site.getUser();

call

function show(a, b){
    alert('this是:'+this+'\na是:'+a+'\nb是:'+b);
}

// show(12, 5);
show.call('abc', 12, 5);       // 'abc' 就是 this

最最简单的继承

function A(){
    this.abc=12;
}

A.prototype.show=function (){
    alert(this.abc);
};

//继承A

function B(){
    A.call(this);    // 必须加上参数 this,否则 A 构造函数中的 this 就会指向 window,然后应当指向的是 new B()
}

B.prototype=A.prototype;

var obj=new B();

obj.show();

引用

// 介绍引用
var arr1=[1,2,3];
var arr2=arr1;
arr2.push(4);

alert(arr1);    //1,2,3,4
alert(arr2);    //1,2,3,4

// 因为引用
function A(){
    this.abc=12;
}
A.prototype.show=function (){
    alert(this.abc);
};


function B(){
    A.call(this);
}
B.prototype=A.prototype;
B.prototype.fn=function (){
    alert('abc');
};

var objA=new A(); 
objA.fn();           // 由于 引用,导致 可以弹出 abc

// 阻止引用
function A(){
    this.abc=12;
}
A.prototype.show=function (){
    alert(this.abc);
};

function B(){
    A.call(this);
}
for(var i in A.prototype){
    B.prototype[i]=A.prototype[i];
}
B.prototype.fn=function (){
    alert('abc');
};

var objB=new B();
var objA=new A();

objA.fn();    //  报错

对象分类

// 本地对象
Object、FunctionArrayStringBooleanNumberDateRegExpError...

// 内置对象
GlobalMath...          // 类似于 静态

// 宿主对象
BOMDOM

高级事件的应用

事件绑定

// 绑定是为了不让事件覆盖
    var oBtn=document.getElementById('btn1');
    /*
    oBtn.onclick=function (){
        alert('a');
    };

    oBtn.onclick=function (){
        alert('b');
    };
    */
    //attachEvent(事件名, 函数)
    //IE
    oBtn.attachEvent('onclick', function (){
        alert('a');
    });
    oBtn.attachEvent('onclick', function (){
        alert('b');
    });

    //FF
    //addEventListener(事件名, 函数, false)
    oBtn.addEventListener('click', function (){
        alert('a');
    }, false);
    oBtn.addEventListener('click', function (){
        alert('b');
    }, false);
function myAddEvent(obj, ev, fn){
    if(obj.attachEvent){
        obj.attachEvent('on'+ev, fn);
    }else{
        obj.addEventListener(ev, fn, false);
    }
}

window.onload=function (){
    var oBtn=document.getElementById('btn1');
    myAddEvent(oBtn, 'click', function (){
        alert('a');
    });
    myAddEvent(oBtn, 'click', function (){
        alert('b');
    });
};

解除绑定

// attachEvent(事件名称, 函数),绑定事件处理函数
detachEvent(事件名称, 函数),解除绑定

// addEventListener(事件名称,函数, 捕获)
removeEventListener(事件名称, 函数, 捕获)

事件捕获

oBtn.setCapture();
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值