分类 JS 下的文章

零JS筆記 | 面向對象 | 組件

   提高对象的复用性
如何配置参数和默认参数
   对面向对象的深入应用(UI组件,功能组件)
   将 配置参数、方法、事件,三者进行分离
创建自定义事件
   有利于多人协作开发代码
   如何去挂载自定义事件与事件函数

組件開發,多組對象;像兄弟之間的關係 (代碼利用的一種形式;)
推理過程:

    function show(opt){
    }
    show({
        id:'div1',
        toDown:function(){},
        toUp:function(){}
    })

    var a = { name:'小明' }  //配置參數   1、優先級較高 2、key值一定要相同 ;
    var b = { name:'小強' }  //默認參數

    extend(b,a) //b的name被a的name覆蓋了;

    console.log(b.name);  //小明,(小強被小明蓋了)

    function extend(o1,o2){
        for(var attr in o2){
            o1[attr] = o2[attr]
        }
    }

重點:寫配置參數---> 寫默認參數--->用配置覆蓋默認---->調用默認方法;

所以,搭架子


var f1 = new Fn();
f1.init({

});

function Fn(){
    
    this.settings = {
            
    }
}
Fn.prototype.init = function(opt){
    extend(this.settings,opt)
}

function extend(o1,o2){
    for(var attr in o2){
        o1[attr] = o2[attr]
    }    
}
//改寫:定義配置參數;
        d1.init({
            id:'div1'
        })

        d2.init({
            id:'div2',
            _down:function(){
                document.title = 'down'
            }
        })
        d3.init({
            id:'div3',
            _down:function(){
                document.title = 'down-down-down'
            },
            _up: function () {
                document.title='up-up-up'
            }
        })
        d4.init({
            id:'div4',
            _up:function(){
                document.title = 'bybybyby'
            }
        })

//沒有值的情況:

    function Drag() {
        this.obj = null;
        this.disX = 0;
        this.dixY = 0;
        this.settings = {    //配置覆蓋默認,然後去調用默認的值;
            _down: function () {},
            _up: function () {}
        }
    }

//執行:

    Drag.prototype.init = function (opt) {
        this.obj = document.getElementById(opt.id)
        var _this = this;

        extend(this.settings, opt)   //使this.settings的值 == opt的值,如果opt沒有,則找默認的

        this.obj.onmousedown = function (ev) {
            var ev = ev || event;
            _this.fnDown(ev)  //ev要傳進來,下面才不用定義 ;

            _this.settings._down()  //調用默認

            document.onmousemove = function (ev) {
                var ev = ev || event;
                _this.fnMove(ev)
            }
            document.onmouseup = function () {
                _this.fnUp();

                _this.settings._up() //調用默認

            }
            return false //最後加阻止默認事件;
        }
    }


//其他:

    Drag.prototype.fnDown = function (ev) {
        this.disX = ev.clientX - this.obj.offsetLeft;
        this.disY = ev.clientY - this.obj.offsetTop;
    }
    Drag.prototype.fnMove = function (ev) {
        this.obj.style.left = ev.clientX - this.disX + 'px'
        this.obj.style.top = ev.clientY - this.disY + 'px'
    }
    Drag.prototype.fnUp = function () {
        document.onmousemove = document.onmouseup = null;
    }
    function extend(o1, o2) {
        for (var attr in o2) {
            o1[attr] = o2[attr]
        }
    }

核心:

//1、寫默認
        this.settings = {
            _down: function () {},
            _up: function () {}
        }
//3、改寫默認,即把外面調用的函數賦值給默認 覆蓋默認,所以再執行如果外面有,則執行,如無則執行默認

        extend(this.settings, opt) 

//2、調執行默認
        _this.settings._down()
        _this.settings._up()

組件彈窗

window.onload = function () {
    var _inp = document.getElementsByTagName('input')
    _inp[0].onclick = function () {
        var d1 = new Dialog();
        d1.init({ //配置參數
            cur: 0,
            title: '登入'
        });
    }
    _inp[1].onclick = function () {
        var d2 = new Dialog();
        d2.init({
            cur: 1,
            w: 100,
            h: 400,
            dir: 'right',
            title: '公告'
        })
    }
    _inp[2].onclick = function () {
        var d2 = new Dialog();
        d2.init({
            cur: 2,
            mask: true
        })
    }
}
function Dialog() {
    this._login = null;
    this._mask = null;
    this.settings = {  //默認參數
        w: 300,
        h: 300,
        dir: 'center',
        title: '',
        mask: false
    }
}
Dialog.prototype.json = {};             //目的:只能彈一次: 先定義空json
Dialog.prototype.init = function (opt) {

    extend(this.settings, opt)

    if (this.json[opt.cur] == undefined) { //第一次走這裏;
        this.json[opt.cur] = true;
    }

    if (this.json[opt.cur]) {       //為true時就走創建
        this.create();
        this.fnClose();
        if (this.settings.mask) {
            this.createMask();
        }
        this.json[opt.cur] = false; //後fase跟undefined也等於false,也不會走上面;
    }
}
Dialog.prototype.create = function () {
    this._login = document.createElement('div');
    this._login.className = 'login'
    this._login.innerHTML = '<div class="title"><span>' + this.settings.title + '</span><span class="close">X</span></div><div class="content"></div>'

    document.body.appendChild(this._login);
    this.setDate();
}
Dialog.prototype.setDate = function () {
    this._login.style.width = this.settings.w + 'px'
    this._login.style.height = this.settings.h + 'px'
    if (this.settings.dir == 'center') {
        this._login.style.left = (viewWidth() - this._login.offsetWidth) / 2 + 'px'
        this._login.style.top = (viewHeight() - this._login.offsetHeight) / 2 + 'px'
    }
    else if (this.settings.dir = 'right') {
        this._login.style.left = (viewWidth() - this._login.offsetWidth) + 'px'
        this._login.style.top = (viewHeight() - this._login.offsetHeight) + 'px'
    }
}
Dialog.prototype.fnClose = function () {
    var _this = this;
    var _close = this._login.querySelector('.close')
    _close.onclick = function () {
        document.body.removeChild(_this._login)
        if (_this.settings.mask) {
            document.body.removeChild(_this._mask)
        }
        _this.json[_this.settings.cur] = true; //關閉後再設回;
    }
}
Dialog.prototype.createMask = function () {
    this._mask = document.createElement('div')
    this._mask.id = 'mask'
    document.body.appendChild(this._mask)
    this._mask.style.width = viewWidth() + 'px'
    this._mask.style.height = viewHeight() + 'px'
}
function viewWidth() {
    return document.documentElement.clientWidth;
}
function viewHeight() {
    return document.documentElement.clientHeight;
}
function extend(o1, o2) {
    for (var attr in o2) {
        o1[attr] = o2[attr]
    }
}

See the Pen avezwe by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

零JS筆記 | 面向對象 | 繼承

继承:在原有對象的基础上,略作修改,得到一个新对象,不影响原对象的功能;
如何添加?
属性继承: 调用父类的构造函数;父类.call(this,参数,参数。。。);
方法继承: 父类的原型直接给子类的原形

function CreatePerson(name, sex) {
    this.name = name;
    this.sex = sex;
}
CreatePerson.prototype.showname = function () {
    console.log(this.name);

}
var p1 = new CreatePerson('小明', '男');
p1.showname();

///CreateStar繼承CreatePerson

function CreateStar(name, sex, job) { //子
//調用相當於執行;调用父类构造函数 ,不加call,则this指向window,必须使用this指向实例;
    CreatePerson.call(this, name, sex) 
    this.job = job;
}
CreateStar.prototype = CreatePerson.prototype

var p2 = new CreateStar('张敬轩', '男', '歌手');

p2.showname()

以上存在问题:一个原型给另一个原型,即对像给对像,所以出现了引用(修改一个会影响另一个;)



一、拷貝繼承;

如何添加?
属性继承: 调用父类的构造函数;父类.call(this,参数,参数。。。);
方法继承: for in形式實現 extend()函數,jq

function CreatePerson(name, sex) {
    this.name = name;
    this.sex = sex;
}
CreatePerson.prototype.showname = function () {
    console.log(this.name);

}
var p1 = new CreatePerson('小明', '男');
p1.showname();

///CreateStar繼承CreatePerson

function CreateStar(name, sex, job) { //子
//調用相當於執行;调用父类构造函数 ,不加call,则this指向window,必须使用this指向实例;
    CreatePerson.call(this, name, sex) 
    this.job = job;
}
//for in繼承
  extend( CreateStar.prototype ,CreatePerson.prototype)

var p2 = new CreateStar('张敬轩', '男', '歌手');

p2.showname()

    function extend(o1,o2){
        for(var attr in o2){
            o1[attr] = o2[attr];
        }
    }
//函數的的特點不能修改,只能重新賦值,所以雖然函數也是對象,但不會出問題;

拖拽繼承小例;

window.onload = function () {
    var d1 = new Drag('div1')
    d1.init()
    var d2 = new ChildDrag('div2')
    d2.init()
}
function Drag(id) {
    this.obj = document.getElementById(id)
    this.disX = 0;
    this.dixY = 0;
}
Drag.prototype.init = function () {
    var _this = this;
    this.obj.onmousedown = function (ev) {
        var ev = ev || event;
        _this.fnDown(ev)  //ev要傳進來,下面才不用定義 ;
        document.onmousemove = function (ev) {
            var ev = ev || event;
            _this.fnMove(ev)
        }
        document.onmouseup = function () {
            _this.fnUp();
        }
        return false //最後加阻止默認事件;
    }
}
Drag.prototype.fnDown = function (ev) {
    this.disX = ev.clientX - this.obj.offsetLeft;
    this.disY = ev.clientY - this.obj.offsetTop;
}
Drag.prototype.fnMove = function (ev) {
    this.obj.style.left = ev.clientX - this.disX + 'px'
    this.obj.style.top = ev.clientY - this.disY + 'px'
}
Drag.prototype.fnUp = function () {
    document.onmousemove = document.onmouseup = null;
}

function ChildDrag(id) {
    Drag.call(this, id) //指向與傳參數
}

//繼承Drag類
extend(ChildDrag.prototype, Drag.prototype);

//繼承後重新改寫move限制範圍;
ChildDrag.prototype.fnMove = function (ev) {
    var L = ev.clientX - this.disX;
    var T = ev.clientY - this.disY;
    if (L < 0) {
        L = 0;
    }
    else if (L > document.documentElement.clientWidth - this.obj.offsetWidth) {
        L = document.documentElement.clientWidth - this.obj.offsetWidth
    }
    this.obj.style.left = L + 'px'
    this.obj.style.top = T + 'px'

}
function extend(o1, o2) {
    for (var attr in o2) {
        o1[attr] = o2[attr]
    }
}



一、類繼承;
利用構造函數的方式;

b1找showName,b1下沒有,但因為賦值(Bbb.prototype = new Aaa();),則通過原型鏈找Bbb.prototype 相當於找 new Aaa(),new Aaa()再通過原型鏈找Aaa.prototype

    //父
    function Aaa() {
        this.name = '小明'
    }
    Aaa.prototype.showName = function () {
        console.log(this.name);
    }
    //子
    function Bbb() {

    }
    //子原型,= 誰去給值給子類原型:父類創建出來的對象 ;
    Bbb.prototype = new Aaa(); //其實也是引用

    var b1 = new Bbb();
    b1.showName()

問題一:constructor

 console.log(b1.constructor);  //變成function Aaa(){}了;修改了;

//修正
 Bbb.prototype = new Aaa(); //其實也是引用
 Bbb.prototype.constructor = Bbb; //修正指向;

問題二:引用時,值的改變會相互影響 ;所以,完整個類繼承的寫法是:

    
    function Bbb(){
        Aaa.call(this)
    }
    
    var F  = function () {}
    F.prototype = Aaa.prototype; //只會給showName,不會接收到屬性;,所以需要設置接收屬性;
    Bbb.prototype = new F();
    Bbb.prototype.constructor = Bbb; //修正指向;

推斷過程:

function Aaa() {
//        this.name = '小明'
    this.name = [1,2,3]
}
Aaa.prototype.showName = function () {
    console.log(this.name);
}
//子
function Bbb() {
    Aaa.call(this)
}
//子原型,= 誰去給值給子類原型:父類創建出來的對象 ;
//  Bbb.prototype = new Aaa(); //其實也是引用
//  Bbb.prototype.constructor = Bbb; //修正指向;

var F  = function () {}
F.prototype = Aaa.prototype; //只會給showName,不會接收到屬性;,所以下面需要設置接收屬性;
Bbb.prototype = new F();
Bbb.prototype.constructor = Bbb; //修正指向;
//屬性與方法的繼承要分開繼承;
var a1 = new Aaa()
var b1 = new Bbb();
b1.showName()
//   console.log(b1);
//b1找showName,b1下沒有,則通過原型鏈找Bbb.prototype 相當於找 new Aaa(),new Aaa()再通過原型鏈找Aaa.prototype

//如何用一句話來完成繼承;
//Bbb.prototype = new Aaa(); 但不坑

b1.name.push(4)
var b2 = new Bbb()
console.log(b1.name);
console.log(b2.name); //也變成1,2,3,4;
console.log(b1.constructor);  //變成function Aaa(){}了;修改了;

所以,属性继承使用call,使用F只继承方法



三、原型繼承

var a = {
    name: '小強'
}
var b = cloneObj(a)

b.name = '小強修改'  //相當於在b下面添加了;所以不需要向後找,
console.log(a.name); //則不會受影響了;

console.log(b.name);
function cloneObj(obj) {
    var F = function () {}
    F.prototype = obj;
    return new F
}

解析:f1 (new出來)通過原型鏈F.pro == obj -->name在obj下面,然後直接return f1 ,則f1 == b;
所以 b找name,相當於b 找f1 ,f1找不到則通過原型鏈F.pro == obj,找到name = '小強'
當給b.name = '小強修改',時,相當於給b下面添加了一個屬性name,則再彈b時不需要沿原型鏈找,所以a.name也不會受影響



繼承三種方法:拷貝、類式、原型;

拷貝:通用型,有new無new都可以;

類式:new構造函數情況;

原型:無new的對象;

當然也有其他繼承:寄生式、、、

零JS筆記 | 面向對象 | 屬性方法

面向對象幾特點:

  • OOP面向對象
  • 抽象:抓核心問題;
  • 封裝:只能通過對象來訪問方法
  • 繼承:從已有對象上繼承出新的對象 //改特殊部分
  • 多態:多對象的不同形態 一個usb接口提供不同功能

對象組成:方法(行為,操作) 函數:過程,動態的
屬性:變量,狀態,靜態;

var arr = []
arr.number = 10;
/* 對象下面的變量叫對象的屬性;*/
console.log(arr.number);
console.log(arr.length);
arr.test = function () { //對象下面的函數叫對象的方法;
    alert(123)
}
arr.test()

//加括號是方法,不加括號是屬性;

    var obj = new Object(); //空對象
    obj.name = '小明';
    obj.show = function () {
        console.log(this.name);
    }
    obj.show()

为对象添加属性和方法
Object对象
this指向
创建两个对象 : 重复代码过多



工廠模式; === 面向對象中的封裝函數
理论上的状态:

    function cPerson(name){
        //原料
        var obj = new Object()
        //加工
        obj.name = name;
        obj.showName = function () {
            console.log(this.name);
        }
        //出廠
       return obj;
    }
   var p1 =  cPerson('小明')
    p1.showName()
    var p2 = cPerson('小強')
    p2.showName()

當new去調用一個函數,這裏函數中的this == 創建出來的對象;而且函數的返回值直接即是this; 隱式返回;
所以問題是:this在哪? 原料是什麼,怎麼加工,出廠後返回值是什麼?

    function CPerson(name){
        //this哪?
        //原料
        //加工
        this.name = name;
        this.showName = function () {
            console.log(this.name);
        }
        //出廠
       // return obj;   //正常的返回沒有return會返回undefined; 如果是用new調用的話,則是返回this;
    }

創建2對象:

var p1 = new CPerson('小強');
var p2 = new CPerson('小明')

    console.log(p1.showName);
    console.log(p2.showName);
    console.log(p1.showName == p2.showName); //false;
//為什麼得false?
//問題:因為引用地址不相同,所以比如創建2000個對象,
//即會有2000個地址,所以必須使用引用相同,變為真;,所以是原型 ;

基本類型比較,對象賦值

    var a = 5 ;
    var b = 5;
    console.log(a === b); //基本類型的比較,只要值相同就行;true;

    var a = [1,2,3];
    var b = [1,2,3];
    console.log(a == b);  //對象 值相同,引用地址不同相同,所以是false;

    var a = [1,2,3]
    var b = a;
    console.log(a == b);   //值相同,引用相同 true;

    var a = [1,2,3]
    var b = a;//對象,把a的值跟地址都給了b 剪切
    b.push(4)
    console.log( b ) //[1,2,3,4]
    console.log( a ) //[1,2,3,4] 

    var a = [1,2,3]
    var b = a;//對象,把a的值跟地址都給了b 剪切
    b = [1,2,3,4]
    console.log( b ) //[1,2,3,4]
    console.log( a ) //[1,2,3] //出現= 必然在內存重新生成地址,所以不會改變a 

原型:原型去改寫對象下面公用的方法或屬性 ;讓公用的方法或屬性在內在中只存在一份,提高性能;

//原型 == class
//普通 == style

自行定義arr.sum方法

     var arr = [1,2,3,4,5]
     var arr2 = [2,3,34,4,23]
     arr.sum = function () {
     var result = 0;
     for(var i=0;i<this.length;i++){
     result += this[i]
     }
     return result;
     }
     console.log(arr.sum())

//原型prototype,寫在構造函數的下面 ;

    var arr = [1,2,3,4,5];
    var arr2 = [2,3,34,4,23]
    Array.prototype.sum = function () {
        var result = 0;
        for(var i=0;i<this.length;i++){
            result += this[i]
        }
        return result;
    }

    console.log(arr.sum());
    console.log(arr2.sum());

    var arr3 = []
    arr3.number = 10; //style
    Array.prototype.number = 20;   //class
    console.log(arr3.number);  //style優先級> class,所以彈出的10 ;



如何把過程寫法改為原型寫法;

 1、原型保存那些不變即公用的屬性及方法;屬性是變化的,則不能放到原型上,所以放到構造函數裏;
 2、
         function 構造函數(){
             this.屬性
          }
         構造函數.原型.方法 = function () {

          }
          var 對象1 = new 構造函數();
          對象1.方法()

總結:相同的属性和方法可以加载原型上,混合的编程模式,构造函数加属性,原型加方法



改寫tab選項卡:

1、不要函數套函數

2、可以有全局變量;

3、把onload中不是賦值的語句放到單獨的函數中;
改成面向對象:全局變量就是屬性;函數就是方法;onload中創建對象;改this指向(在事件或定時器時this指向易被改 )

function Tab(id) {
    this.box = document.getElementById(id);
    this.btn = this.box.getElementsByTagName('input')
    this.div = this.box.getElementsByTagName('div')
    this.num = 0;
}
Tab.prototype.init = function () {
    var _this = this;
    for (var i = 0; i < this.btn.length; i++) {
        this.btn[i].index = i;
        this.btn[i].onclick = function () {
            _this.change(this)  // //this是按鈕的this  _this是對像,即change由對象調用,所以下面的this不換;正確了
        };
    }
}
Tab.prototype.change = function (obj) { //change是在init調用,所以this指向init裏,必須修改
    for (var j = 0; j < this.btn.length; j++) {
        this.btn[j].className = ''
        this.div[j].style.display = 'none'
    }
    obj.className = 'on'  //傳進來按鈕的this
    this.div[obj.index].style.display = 'block' //傳進來按鈕的this
}
Tab.prototype.autoplay = function () {
    var _this = this;
    setInterval(function () {
        if (_this.num == _this.btn.length - 1) {
            _this.num = 0;
        }
        else {
            _this.num++
        }

        for (var j = 0; j < _this.btn.length; j++) {
            _this.btn[j].className = ''
            _this.div[j].style.display = 'none'
        }
        _this.btn[_this.num].className = 'on'  //傳進來按鈕的this
        _this.div[_this.num].style.display = 'block' //傳進來按鈕的this
    }, 1000)

}
<div id="box">
    <input type="button" value="1" class="on"/>
    <input type="button" value="2"/>
    <input type="button" value="3"/>
    <div style="display: block;">0001</div>
    <div>0002</div>
    <div>0003</div>
</div>

ev只能出現在事件函數中;return false 也要出現在事件函數中

  ---
    this._div.onmousedown = function(){
    This.fnDown()
    }
  --
    Drag.prototype.fnDown = function(ev){
        var ev = ev || event; 

    return false 
    }

//以上報錯;正確是:

  ---
    this._div.onmousedown = function(ev){ //事件函數
    var ev = ev || event; 
    This.fnDown(ev)
    return false 
    }
  --
    Drag.prototype.fnDown = function(ev){

    }



包裝對象;

    //包装对象 ;
    var str = 'hello'  //是类型,不是对像
    str.charAt(0)   //当调用方法时,基本类型会找到对象的包装对象类型,然后包装把所有的属性方法都给基本类型,然后包装对象消失;
    //包装对象送快递,送完后即有里面的东西
    str.indexOf('e')

//所以問題是:    console.log(typeof str); //string;不是对象;
//字符串怎么有方法 ? charAt(0)?
基本类型都有自己对应的包装对象:String Number Boolean; Array Date对象中的构造函数;这些类型怎么创建对象 ;

var str2 = new String('hello')
console.log(typeof str2) //這裏是obj了,即通過new創建的都是對象;
console.log(str.charAt(1))//所以有對象;

//String.prototype.chatAt = function(){}


當
var str = 'hello'  //這裏是字符串

str.charAt(0); //當字符串調方法時:基本類型會找到對應的包裝對像string對像,string下有原型方法 string.protype.charAt = function() {};

如何給字符串加方法?

String.prototype.lastValue = function(){
    return this.chatAt(this.lenght - 1)
}
var str3 = 'hello'
console.log( str3.laseValue() ) //o

注意:

var str = 'hello'
str.number = 10 ; //通过包装对象string添加,加完后包装对象消失

alert(str.number) //所以这里弹undefined ,如须使有效果须加在原型上:String.prototype.number = 10

如何給基本類型加屬性?
基本类型要加一个属性,到这里程序会找包装对象,然后在包装对象里创建一个对象,包装对象消失;然后再调用 str4.number时,其它会重新创建又一个对象,所以找不到是undefined; (没有加到原型里的情况;)

var str4  = 'hello'; 
str4.number = 10;
console.log(str4.number) //undefined;

當然如果通過new創建則是10,或直接加到原型 String.prototype.number = 10,也是10


原型鏈 _proto_ :【实例对象】与【原型】之间的连接,叫原型链
当a1调用num,基本a1是找不到的,找不到怎样----》再找原型链;_proto_

原型链的最外层是object;

    //实例对象与原型之间的连接,叫原型链
    function Aaa() {
        // this.num = 20;
    }
    //   Aaa.prototype.num = 10;  //Aaa.prototype即一个对象    //num即原型对象下的一个属性
    var a1 = new Aaa();                //实例对象
    Object.prototype.num = 30            
    console.log(a1.num);                                //之间的链接



面向對象的屬性:

hasownprototy:判斷屬性是否屬於 對象自身下面的屬性 [只有自己有,別人不能有的]

var arr = [];
    arr.num = 10;
Array.prototype.num2 = 20;
console.log(arr.hasOwnproperty('num')) //true;
console.log(arr.hasOwnproperty('num2')) //false,不是arr數組獨有;
function Bbb(){}

var b1 = new Bbb();
console.log(b1.hasOwnProoerty) ///究竟在哪;在原型链接下,object.prototype上,在顶部上;

console.log(b1.hasOwnProperty == Object.prototype.hasOwnProperty ) //true;

constructor: 查看對象構造函數,即由哪個函數構造出來的實例;

function Aaa(){}
var a1 = new Aaa();
console.log( a1.constructor ) //彈出本身的屬性,a1由哪個函數造出來的; function Aaa(){}

var arr2 = []
console.log( arr2.constructor ) //function Array() { [native code] } //私有方法看不到;

可以用來作判斷:

console.log( arr2.constructor == Array )  //true;


constructor怎麼來的?

當寫一個構造函數function Aaa(){ }
寫完後,即會自動生成: Aaa.prototype.constructor == Aaa 自動添加;

//當手動寫時,
var aa1 = new Aaa()
Aaa.prototype.constructor == Array; //一般不要去改,了解即可;

//則會自動生成的覆蓋了;
console.log(aa1.constructor == Array) //true;

<quoteblock>
只有constructor屬性才是程序自動生成的,每個函數都會生成,其他的不是 ;
</quoteblock>

//b1调用的其实不是自身的,而是最外层的;
console.log(b1.constructor.hasOwnProperty);


不經意改掉constructor情況;

function Ccc(){}
Ccc.prototype.num = 10;
Ccc.prototype.name = '小強'
Ccc.prototype.age = 20
console.log(c1.constructor); //function Ccc(){}

Ccc.prototype是一個對象,所以可寫成json形式:

Ccc.prototype = { //即把Ccc.prototype=  重新赋值,所以constructor会改
    name:'小強',
    age:20
}
var c1 = new Ccc();
console.log(c1.constructor)
 //function Object(){}找的就是json对应的constructor了,全覆盖上一条条自动生成的constructor

所以,constructor變成Object了,需要修正constructor指向,使之指回調用的函數;

    Ccc.prototype = {
        constructor : Ccc,
        name:'小明',
        age : 20
    }


for in 時,系統自動的屬性是for in不到的;
1、系統自添加的屬性;

function Ddd(){}
var d1 = new Ddd();
for(var attr in Ddd.prototype){
       console.log('能打印出來嗎?不能!')
}

2、自定義的屬性;

Ddd.prototype.name = 'abc';
for(var attr in Ddd.prototype){
        console.log('這裏是可打印出來的,即能找到;')
}

3、自定義的constructor屬性

Ddd.prototype.constructor = Aaa
for(var attr in Ddd.prototype){
        console.log(attr) //也不能打印出來;
}



instanceof運算符;
對象與構造函數在原型鏈接上是否有關係;

    function Eee(){}
    var e1 = new Eee()
    console.log(e1 instanceof Eee); //true;是否在同一个原型链接上;
    console.log(e1 instanceof Array); //false;是否在同一个原型链接上;
    console.log(e1 instanceof Object); //true;是否在同一个原型链接上;每一个对象最外层都是true; 任何对象 instanceof都为true;

所以,除constructor外;instanceof也可使類型判斷;

arr instanceof Array  //true;


类型判断三方法: constructor instanceof toString



問題:如何判斷一個變量是一個數組;
toString() Object方法;
toString在哪;系统对像下面都是自带的,自已写的对象都是通过原型链接找Object下面的;

var arr4 = []
console.log(arr4.toString) //可找到;function toString(){}
console.log(arr4.toString == Object.prototype.toString) //系統對象false;
function Fff(){}
var f1 = new Fff();
console.log(f1.toString) //toString在Object上;
console.log(f1.toString == Object.prototype.toString); //自已写的对象 true;

toString(),把对象转成字符串;

var arr5 = [1,2,3]
console.log(typeof arr5.toString())  //string
console.log(arr5.toString()); // [1,2,3]与数组一样的形式;

自己写可以需要写成自己的形式:

console.log('111' + typeof arr5);//还是Object,不会改变自身;
    Array.prototype.toString = function () {
        return this.join('+')
    }

    console.log(arr5.toString());
    '1+2+3'

進制轉換;

    var num6= 255;
    console.log(num6.toString(16)); //ff,转成16进制;
    console.log(num6.toString(2)); //11111111,转成2进制;

最重要的類型判斷;完美版;

var arr7 = []
    console.log(Object.prototype.toString.call(arr7)); //[object Array]
    var arr8 = {}
    console.log(Object.prototype.toString.call(arr8)); //[object Object]
    var arr9 = new Date()
    console.log(Object.prototype.toString.call(arr9)); //[object Date]
    var arr10 = new RegExp()
    console.log(Object.prototype.toString.call(arr10)); //[object RegExp]
    var arr11 = null;
    console.log(Object.prototype.toString.call(arr11)); //[object Null]

所以,判斷方法是:

console.log(Object.prototype.toString.call(arr7) == '[object Array]');

總結:判斷類型的三種方法,constructor,instanceof, toString.call()
前兩種在某些情況可能不行,如iframe

    window.onload = function () {
        var _f = document.createElement('iframe');
        document.body.appendChild(_f)
        var _farray = window.frames[0].Array //frames集合第0个,.Array找到iframe下面的Array,
        var arr = new _farray();//其实是跨页面了;

        console.log(arr.constructor == Array); //false 跨iframe里失效,但实际上确实是数组;
        console.log(arr instanceof Array); //false 也失效;
        console.log(Object.prototype.toString.call(arr) == '[object Array]');
        // true了;
    }

backbone 未入門

資源:

backbone中文檔


underscore中文檔

一个实现了web前端MVC模式的JS库
M : model (模型)
V : view (试图)
C : controller (控制器)
就是把模型与视图分离,通过控制器来连接他们
模塊:

Events : 事件驱动方法
Model : 数据模型
Collection : 模型集合器
Router : 路由器(hash)
History : 开启历史管理
Sync : 同步服务器方式
View : 试图(含事件行为和渲染页面)

1)直接創建對像:

/*
var models = new Backbone.Collection;
var views = new Backbone.View;
*/
var model = new Backbone.Model;
model.set('name','hello')
console.log(model.get('name'));

2)给构造函数添加实例方法和静态方法

    var m_1 = new Backbone.Model({'name':'hello'})
    var m_2 = new Backbone.Model({'name':'hi'})
    var coll = new Backbone.Collection()
    coll.add(m_1)
    coll.add(m_2)
    console.log(JSON.stringify(coll)); // 對象解析出字符串;

//Backbone.Model表示模型的構造函數,extend參數 ({json實例方法},{json靜態方法})

    var M = Backbone.Model.extend({
        aaa:function(){
            console.log(123);
        }
    },{
        bbb: function () {
            console.log(456);

        }
    })
    var model = new M
    model.aaa() //實例方法使用實例調用;
    M.bbb();  //靜態使用構造函數直接調用;即相當於多了一個命名空間而已;

//設置默認值:
    var M = Backbone.Model.extend({
        defaults:{
            name:'hello'
        }
    })
    var mo_= new M;
    console.log(mo_.get('name'));

3)继承操作

    var M = Backbone.Model.extend({
        aaa: function () {
            console.log('abc');
        }
    },{
        bbb: function () {
            console.log('def');
        }

    })
    var ChildM = M.extend();
    var mo = new ChildM
    mo.aaa()
    ChildM.bbb()

4)自定义事件

(function () {
    var M = Backbone.Model.extend({
        defaults:{
            name:'hello'
        },
        initialize:function(){
            this.on('change', function () {
                console.log('onchange觸發了');
            })
        }
    })
    var model = new M
    model.set('name','hi')
})();
//指定key值觸發;
(function () {
    var M = Backbone.Model.extend({
        defaults:{
            name:'hello'
        },
        initialize:function(){
            this.on('change:name', function (model) {  //不同的key值觸發;
                console.log(model);
            })
        }
    })
    var model = new M
    model.set('name','hi')
})();


//1、創建模型對像
//2、創建視圖對像,直接在視圖對象裏傳參,指定模型對像,即連接在一起;
//3、對模型修改時,即會觸發視圖對象;

var M = Backbone.Model.extend({
    defaults: {
        name: 'hello'
    }
});

var V = Backbone.View.extend({
    initialize: function () {
        this.listenTo(this.model, 'change', this.show);
    },
    show: function (model) {
        $('body').append('<div>' + model.get('name') + '</div>')
    }
});

var m = new M;          //1、創建模型對像
var v = new V({model: m});  //2、創建視圖對像,直接在視圖對象裏傳參,指定模型對像,即連接在一起;
m.set('name', 'hi')  //3、對模型修改時,即會觸發視圖對象;

5)數據與服務器


(function () {
    Backbone.sync = function (method, model) {
        console.log(method + ': ' + JSON.stringify(model));
        model.id = 1;
    }
    var M = Backbone.Model.extend({
        defaults:{
            name:'hello'
        },
        url:'/user' // ajax提交,一定要指定好url ;
    });
    var m = new M;
    m.save(); //把現在的模型對象保存到服務器上;
    m.save({name:'hi'});  //修改
})();

(function () {
    Backbone.sync = function (method, model) {
        console.log(method + ': ' + JSON.stringify(model));
    }
    var C = Backbone.Collection.extend({
        initialize: function () {
            this.on('reset', function () {
                console.log(123);
            })
        },
        url:'/user' // ajax提交,一定要指定好url ;
    });
    var m = new C;
    m.fetch() //讀取服務器數據;
})();

6)路由與歷史管理

(function () {
    var Workspace = Backbone.Router.extend({
        routes:{
            'help':             'help',
            'search/:query':    'search',  //#search/任意字符;
            'search/:query/p:page': 'search' //#search//kiwis/p7
        },
        help: function () {
            console.log(1);
        },
        search: function (query,page) {
            console.log(2);
        }

    })
    var w = new Workspace
    Backbone.history.start()
    /*
    * 地址後面加#help,彈1;
    * 地址後面加#search/dfk 彈2
    *
    * */
})();

7)事件委託

所有的视图都拥有一个 DOM 元素(el 属性),即使该元素仍未插入页面中去。 视图可以在任何时候渲染,然后一次性插入 DOM 中去,这样能尽量减少 reflows 和 repaints 从而获得高性能的 UI 渲染。 this.el 可以从视图的 tagName, className, id 和 attributes 创建,如果都未指定,el 会是一个空 div。

(function () {
    var V = Backbone.View.extend({
        el:$('body'), //觸發的委託人;
        events:{
            'click input':'aaa',
            'mouseover li':'bbb'
        },
        aaa: function () {
            console.log(1111111);
        },
        bbb: function () {
            console.log(2221222);
        }
    })
    var veiw = new V;
})();



8)前端模板

$(function () {

    var M = Backbone.Model.extend({
        defaults:{
            name:'hello'
        }
    })
    var V = Backbone.View.extend({
        initialize: function () {
            this.listenTo(this.model,'change',this.show)
        },
        show: function (model) {
            $('body').append(this.template(this.model.toJSON()))
        },
        template: _.template($('#template').html())
    })

    var m = new M;
    var v = new V({model:m})
    m.set('name','hdi')
})

調用:

<script type="text/template" id="template">
    <% for(var i=0;i<5;i++) { %>
    <div><%= name %></div>
    <% } %>
</script>


大部分操作:

首先頁面上先對【數據進行修改】 ----> 數據修改包括【模型修改】或【集合修改】--->

當這兩個修改後---> 會觸發相應的【自定義事件】--->

自定義事件找到相應---> 【視圖】--->

回調函數更新視圖----> 視圖的更新通過前端模板獲取到,再生成到---->頁面;

一個模型和一個集合,一個模型對應一個視圖,集合對應大視圖;


<script>
var f = 1;
document.getElementById('tdosclick').onclick = function(){
if(f){

document.getElementById('tdos').style.display = 'block';

}
else{
document.getElementById('tdos').style.display = 'none';
}
f = !f;
}
</script>

零JS筆記 | 三角函数

函數:每一個變量都有對應的值稱之為函數


Math.pow(a,b) 表示ab</sup


Math.sqrt(a),表示a的開方,無法開多次方


a2+b2=c2


iMac底部菜單


See the Pen PPENEj by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>



三角函数:Math.sin(弧度)、Math.cos(弧度)、Math.tan(弧度),即三角函数括号里以弧度为单位;


360o == 2π弧度; 所以,1弧度 = 180/π角度,1角度 = π/180弧度,记忆:弧度 > 角度


角度转弧度: π/180 × 角度


弧度变角度: 180/π × 弧度


sin = a/c;cos = b/c; tan = a/b


圆的周长:l = 2π*r


弧长等于半径的弧,其所对的圆心角为1弧度,所以: 弧长=nπr/180,在这里n就是角度数,即圆心角n所对应的弧长


一周的弧度数为2πr/r=2π,360°角=2π弧度,因此,1弧度约为57.3°,即57°17'44.806'',1°为π/180弧度,近似值为0.01745弧度,周角为2π弧度,平角(即180°角)为π弧度,直角为π/2弧度。

//角度转弧度,30度角转弧度,30*π/180
Math.sin(30 * Math.PI/180)

//上下比,角度对应π,弧度对应180


圓周運動,右水平線開始運動;

window.onload = function(){
    var oDiv = document.getElementById('div1');
    var r = 100;
    var x = 700;
    var y = 300;
    var num = 0;
    setInterval(function(){
        num++
        //Math.sin( num*Math.PI/180 ) = a/r;
        //Math.cos( num*Math.PI/180 ) = b/r;
        
        var a = Math.sin( num*Math.PI/180 ) * r; //顺时针时,距离中心点的top值越来越远
        var b = Math.cos( num*Math.PI/180 ) * r; //顺时针时,距离中心点的left值越来越近;

        oDiv.style.left = x + b + 'px';
        oDiv.style.top = y + a + 'px';
        
        var oBox = document.createElement('div');
        oBox.className = 'box';
        document.body.appendChild( oBox );
        
        oBox.style.left = oDiv.offsetLeft + 'px';
        oBox.style.top = oDiv.offsetTop + 'px';
    },300);
};
#div1{ width:20px; height:20px; background:red; position:absolute; left:800px; top:300px;}
.box{ border:1px #000 solid; position:absolute;}

围绕y轴,在x轴平面上做运动,并且有z轴半径r;所以top值不变,改变的是left值与宽高,形成视觉差,近大远小运动

window.onload = function(){
    var oDiv = document.getElementById('div1');
    var r = 100;
    var x = 700;
    var y = 300;
    var num = 0;
    setInterval(function(){
        num++
        //Math.sin( num*Math.PI/180 ) = a/r;
        //Math.cos( num*Math.PI/180 ) = b/r;

        //围绕y轴,在x轴平面上做运动,并且有z轴半径r;所以top值不变,改变的是left值与宽高,形成视觉差,近大远小运动
        
        var a = Math.sin( num*Math.PI/180 ) * r;
        var b = Math.cos( num*Math.PI/180 ) * r;

        oDiv.style.left = x + b + 'px';
        //oDiv.style.top = y + a + 'px';
        
        oDiv.style.width = a/100*30 + 50 + 'px'; //a最大100,起点50,注意理解
        oDiv.style.height = a/100*30 + 50 + 'px';

    },8);
};

圆心随鼠标移动方向移动;

var box = document.querySelector('.box')
var ege = document.querySelector('.ege')
var r = 50;
var L = 400
var T = 400
/*     -
     *     \
           \
    - ------------  +
           \
           \
    *      +
    * */
document.onmousemove = function (e) {
  var e = e || event;
  var x = e.clientX;
  var y = e.clientY;
  var a = Math.abs(x - (L + ege.parentNode.offsetLeft)) //为算角度
  var b = Math.abs(y - (T + ege.parentNode.offsetTop)) //大角与小角 角度一样
  var changeX = 0;
  var changeY = 0;
  if (x > L + ege.parentNode.offsetLeft && y < T + ege.parentNode.offsetTop) {
    changeX = Math.sin(Math.atan(b / a)) * r
    changeY = Math.cos(Math.atan(b / a)) * - r
  } 
  else if (x > L + ege.parentNode.offsetLeft && y > T + ege.parentNode.offsetTop) {
    changeX = Math.sin(Math.atan(b / a)) * r
    changeY = Math.cos(Math.atan(b / a)) * r
  } 
  else if (x < L + ege.parentNode.offsetLeft && y > T + ege.parentNode.offsetTop) {
    changeX = Math.sin(Math.atan(b / a)) * - r
    changeY = Math.cos(Math.atan(b / a)) * r
  } 
  else if (x < L + ege.parentNode.offsetLeft && y < T + ege.parentNode.offsetTop) {
    changeX = Math.sin(Math.atan(b / a)) * - r
    changeY = Math.cos(Math.atan(b / a)) * - r
  }
  ege.style.left = changeX + 'px'
  ege.style.top = changeY + 'px'
}

使用Math.atan2(y,x),以原点为基础,任意一点到原点x轴的夹角;值范围为-PI - PI,换角度即:-180 - 180



一图了然,所以改写为

var ev = ev || window.event;
change(oDiv2, ev.clientX, ev.clientY, L2, T2);
change(oDiv3, ev.clientX, ev.clientY, L3, T3);
function change(obj, x, y, l, t) {
  var changeX = 0;
  var changeY = 0;

  var a = x - (obj.offsetLeft + obj.parentNode.offsetLeft)    //方向 右+ 左- 上 + 下-
  var b = - (y - (obj.offsetTop + obj.parentNode.offsetTop))

  var ifm = Math.atan2(b, a) * 180 / Math.PI

  if (0 < ifm < 90) {
    changeX = Math.sin(Math.atan2(b, a)) * r
    changeY = Math.cos(Math.atan2(b, a)) * r
  } 
  else if (90 < ifm < 180) {
    changeX = Math.sin(Math.atan2(b, - a)) * r
    changeY = Math.cos(Math.atan2(b, - a)) * r
  } 
  else if (0 > ifm > - 90) {
    changeX = Math.sin(Math.atan2( - b, a)) * r
    changeY = Math.cos(Math.atan2( - b, a)) * r
  } 
  else if ( - 90 > ifm > - 180) {
    changeX = Math.sin(Math.atan2( - b, - a)) * r
    changeY = Math.cos(Math.atan2( - b, - a)) * r
  }

  obj.style.left = l + changeX + 'px';
  obj.style.top = t + changeY + 'px';
}


反正弦,反余弦 Math.asin(x); Math.acos(x) 求度数函数


正常sin30度=1/2 arcsin2/1=30度

cos60度=1/2 arccos1/2=30度



<style>

table{border-collapse: collapse;width:95%}
table td{border:1px solid #ddd;padding:5px 10px}
table th{border:1px solid #ddd;padding:5px 10px}

</style>

Math 对象属性

属性 描述
E 返回算术常量 e,即自然对数的底数(约等于2.718)。
LN2 返回 2 的自然对数(约等于0.693)。
LN10 返回 10 的自然对数(约等于2.302)。
LOG2E 返回以 2 为底的 e 的对数(约等于 1.414)。
LOG10E 返回以 10 为底的 e 的对数(约等于0.434)。
PI 返回圆周率(约等于3.14159)。
SQRT1_2 返回返回 2 的平方根的倒数(约等于 0.707)。
SQRT2 返回 2 的平方根(约等于 1.414)。

Math 对象方法

方法 描述
abs(x) 返回数的绝对值。
acos(x) 返回数的反余弦值。
asin(x) 返回数的反正弦值。
atan(x) 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。
atan2(y,x) 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。
ceil(x) 对数进行上舍入。
cos(x) 返回数的余弦。
exp(x) 返回 e 的指数。
floor(x) 对数进行下舍入。
log(x) 返回数的自然对数(底为e)。
max(x,y) 返回 x 和 y 中的最高值。
min(x,y) 返回 x 和 y 中的最低值。
pow(x,y) 返回 x 的 y 次幂。
random() 返回 0 ~ 1 之间的随机数。
round(x) 把数四舍五入为最接近的整数。
sin(x) 返回数的正弦。
sqrt(x) 返回数的平方根。
tan(x) 返回角的正切。
toSource() 返回该对象的源代码。
valueOf() 返回 Math 对象的原始值。

零JS筆記 | javascript運動 | 时间版

jq的animate是典型的时间版框架 默認400ms


如中间放大,改width,height,left,top值

sMove2(this,{width:200,height:200,left:150,top:150})

出现的bug,快结束时会抖动,速度没变,但移动距离变,所以时间上先后到达存在问题;


时间版算法根据Tween算法而来;


参考:http://www.cnblogs.com/bluedream2009/archive/2010/06/19/1760909.html


初始化: t = 時間,【可變】,b,初始值,c改變量,d:總時間 return目標點


如:div初始100,2s内变化到200,则,t = 0~2; b:100,c:200-100,d:2s;

var Tween = {
    linear: function (t, b, c, d){  //匀速  
      return c*t/d + b;
    },
    ....

因为可能多个值,所以设置iCur变量为{},然后再for循环,初始化一0,判断是否opacity,初始化二:获取传值数据;

function tMove(obj, json,times,fx,fn) {
    var iCur = {};//不變,不能寫在定時器裏  b
    for(var attr in json){
        iCur[attr] = 0;
        if(attr=='opacity'){
            iCur[attr] = Math.round(getStyle(obj.attr)*100)
        }
        else{
            iCur[attr]=parseInt(getStyle(obj.attr));
        }
    }
    clearInterval(obj._t)
    obj._t = setInterval(function () {
        for(var attr in json){
            var value = Tween[fx](t,b,c,d) //目的,通過js獲取tbcd值
            if(attr == 'opacity'){
                obj.style.opacity = value/100;
                obj.style.filter = 'alpha(opacity='+value+')';

            }
            else{
                obj.style[attr] = value +'px'  //value是不断变化的值,即Tween return回来的结果;
            }
        }
    },13)
}

以上说明即目的:获取在Tween内,tbce参数的值,之后再返回结果给value;


注意:设置定时器时,还需要一个循环;

function tMove(obj, json, times, fx, fn) {
    if (typeof times == 'undefined') {
        times = 400;
        fx = 'linear';
    }
    if (typeof times == 'string') {
        if (typeof fx == 'function') {
            fn = fx;
        }
        fx = times;
        times = 400;
    }
    else if (typeof times == 'function') {
        fn = times;
        times = 400;
        fx = 'linear';
    }
    else if (typeof times == 'number') {
        if (typeof fx == 'function') {
            fn = fx;
            fx = 'linear';
        }
        else if (typeof fx == 'undefined') {
            fx = 'linear';
        }
    }
    var iCur = {
    }; //不變,不能寫在定時器裏  b
    for (var attr in json) {
        iCur[attr] = 0;
        if (attr == 'opacity') {
            iCur[attr] = Math.round(css(obj, attr) * 100);
        }
        else {
            iCur[attr] = parseInt(css(obj, attr));
        }
    }
    var startTime = now();
    clearInterval(obj._t);
    obj._t = setInterval(function () {
        var changeTime = now();
        var t = times - Math.max(0, startTime - changeTime + times);
        //在time的範圍內越來越小  2000-0;
        for (var attr in json) {
            var value = Tween[fx](t, iCur[attr], json[attr] - iCur[attr], times); //目的,通過js獲取tbcd值
            if (attr == 'opacity') {
                obj.style.opacity = value / 100;
                obj.style.filter = 'alpha(opacity=' + value + ')';
            }
            else {
                obj.style[attr] = value + 'px';
            }
        }
        if (t == times) {
            clearInterval(obj._t);
            fn && fn.call(obj);
        }
    }, 13)
}
function now() {
    return (new Date()).getTime();
}
var Tween = {
    linear: function (t, b, c, d) { //匀速
        return c * t / d + b;
    },
    easeIn: function (t, b, c, d) { //加速曲线
        return c * (t /= d) * t + b;
    },
    easeOut: function (t, b, c, d) { //减速曲线
        return - c * (t /= d) * (t - 2) + b;
    },
    easeBoth: function (t, b, c, d) { //加速减速曲线 缓冲
        if ((t /= d / 2) < 1) {
            return c / 2 * t * t + b;
        }
        return - c / 2 * ((--t) * (t - 2) - 1) + b;
    },
    easeInStrong: function (t, b, c, d) { //加加速曲线
        return c * (t /= d) * t * t * t + b;
    },
    easeOutStrong: function (t, b, c, d) { //减减速曲线
        return - c * ((t = t / d - 1) * t * t * t - 1) + b;
    },
    easeBothStrong: function (t, b, c, d) { //加加速减减速曲线
        if ((t /= d / 2) < 1) {
            return c / 2 * t * t * t * t + b;
        }
        return - c / 2 * ((t -= 2) * t * t * t - 2) + b;
    },
    elasticIn: function (t, b, c, d, a, p) { //正弦衰减曲线(弹动渐入)
        if (t === 0) {
            return b;
        }
        if ((t /= d) == 1) {
            return b + c;
        }
        if (!p) {
            p = d * 0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        } else {
            var s = p / (2 * Math.PI) * Math.asin(c / a);
        }
        return - (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
    },
    elasticOut: function (t, b, c, d, a, p) { //正弦增强曲线(弹动渐出)
        if (t === 0) {
            return b;
        }
        if ((t /= d) == 1) {
            return b + c;
        }
        if (!p) {
            p = d * 0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        } else {
            var s = p / (2 * Math.PI) * Math.asin(c / a);
        }
        return a * Math.pow(2, - 10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b;
    },
    elasticBoth: function (t, b, c, d, a, p) {
        if (t === 0) {
            return b;
        }
        if ((t /= d / 2) == 2) {
            return b + c;
        }
        if (!p) {
            p = d * (0.3 * 1.5);
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        }
        else {
            var s = p / (2 * Math.PI) * Math.asin(c / a);
        }
        if (t < 1) {
            return - 0.5 * (a * Math.pow(2, 10 * (t -= 1)) *
                    Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
        }
        return a * Math.pow(2, - 10 * (t -= 1)) *
                Math.sin((t * d - s) * (2 * Math.PI) / p) * 0.5 + c + b;
    },
    backIn: function (t, b, c, d, s) { //回退加速(回退渐入)
        if (typeof s == 'undefined') {
            s = 1.70158;
        }
        return c * (t /= d) * t * ((s + 1) * t - s) + b;
    },
    backOut: function (t, b, c, d, s) {
        if (typeof s == 'undefined') {
            s = 3.70158; //回缩的距离
        }
        return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
    },
    backBoth: function (t, b, c, d, s) {
        if (typeof s == 'undefined') {
            s = 1.70158;
        }
        if ((t /= d / 2) < 1) {
            return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
        }
        return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
    },
    bounceIn: function (t, b, c, d) { //弹球减振(弹球渐出)
        return c - Tween['bounceOut'](d - t, 0, c, d) + b;
    },
    bounceOut: function (t, b, c, d) {
        if ((t /= d) < (1 / 2.75)) {
            return c * (7.5625 * t * t) + b;
        } else if (t < (2 / 2.75)) {
            return c * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75) + b;
        } else if (t < (2.5 / 2.75)) {
            return c * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375) + b;
        }
        return c * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375) + b;
    },
    bounceBoth: function (t, b, c, d) {
        if (t < d / 2) {
            return Tween['bounceIn'](t * 2, 0, c, d) * 0.5 + b;
        }
        return Tween['bounceOut'](t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b;
    }
}
function css(obj, attr) {
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj) [attr]
}

See the Pen vNWQej by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>



在瀏覽器中,若定時器處於運動狀態時切換到其他頁面,如最小化,切換到其他標籤等操作,瀏覽器會默認將定時器走得很慢,可能出現bug,可使用window.onfocus && window.onblur解決;按實際情獎況而訂;




不可避免的JQ animate()擴展

$(function () {
$('#div1').click(function () {
    $(this).animate({width:200,height:200},2000,'bounceIn')
})
$.extend(jQuery.easing,{
    easeIn: function(x,t, b, c, d){  //加速曲线
        return c*(t/=d)*t + b;
    },
    easeOut: function(x,t, b, c, d){  //减速曲线
        return -c *(t/=d)*(t-2) + b;
    },
    easeBoth: function(x,t, b, c, d){  //加速减速曲线
        if ((t/=d/2) < 1) {
            return c/2*t*t + b;
        }
        return -c/2 * ((--t)*(t-2) - 1) + b;
    },
    easeInStrong: function(x,t, b, c, d){  //加加速曲线
        return c*(t/=d)*t*t*t + b;
    },
    easeOutStrong: function(x,t, b, c, d){  //减减速曲线
        return -c * ((t=t/d-1)*t*t*t - 1) + b;
    },
    easeBothStrong: function(x,t, b, c, d){  //加加速减减速曲线
        if ((t/=d/2) < 1) {
            return c/2*t*t*t*t + b;
        }
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    elasticIn: function(x,t, b, c, d, a, p){  //正弦衰减曲线(弹动渐入)
        if (t === 0) {
            return b;
        }
        if ( (t /= d) == 1 ) {
            return b+c;
        }
        if (!p) {
            p=d*0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p/4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    },
    elasticOut: function(x,t, b, c, d, a, p){    //正弦增强曲线(弹动渐出)
        if (t === 0) {
            return b;
        }
        if ( (t /= d) == 1 ) {
            return b+c;
        }
        if (!p) {
            p=d*0.3;
        }
        if (!a || a < Math.abs(c)) {
            a = c;
            var s = p / 4;
        } else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
    },
    elasticBoth: function(x,t, b, c, d, a, p){
        if (t === 0) {
            return b;
        }
        if ( (t /= d/2) == 2 ) {
            return b+c;
        }
        if (!p) {
            p = d*(0.3*1.5);
        }
        if ( !a || a < Math.abs(c) ) {
            a = c;
            var s = p/4;
        }
        else {
            var s = p/(2*Math.PI) * Math.asin (c/a);
        }
        if (t < 1) {
            return - 0.5*(a*Math.pow(2,10*(t-=1)) *
                    Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        }
        return a*Math.pow(2,-10*(t-=1)) *
                Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b;
    },
    backIn: function(x,t, b, c, d, s){     //回退加速(回退渐入)
        if (typeof s == 'undefined') {
            s = 1.70158;
        }
        return c*(t/=d)*t*((s+1)*t - s) + b;
    },
    backOut: function(x,t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 3.70158;  //回缩的距离
        }
        return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
    },
    backBoth: function(x,t, b, c, d, s){
        if (typeof s == 'undefined') {
            s = 1.70158;
        }
        if ((t /= d/2 ) < 1) {
            return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
        }
        return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
    },
    bounceIn: function(x,t, b, c, d){    //弹球减振(弹球渐出)
        return c - this['bounceOut'](x,d-t, 0, c, d) + b;
    },
    bounceOut: function(x,t, b, c, d){
        if ((t/=d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b;
        }
        return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b;
    },
    bounceBoth: function(x,t, b, c, d){
        if (t < d/2) {
            return this['bounceIn'](x,t*2, 0, c, d) * 0.5 + b;
        }
        return this['bounceOut'](x,t*2-d, 0, c, d) * 0.5 + c*0.5 + b;
    }

})
})

零JS筆記 | javascript運動 | 弹性 | 碰撞

運動公式:


弹性:速度+=(目标点-当前值)/系数 必須是全局变量

速度*=摩擦系数[小于1]

缓冲:
var 速度 = (目标点-当前值)/系数 局部變量

速度取整

系數取值:
系数: 6,7,8
摩擦系数:0.75

運動的基本步驟:


1、清除定時器;

2、開定定時器:寫條件...

寫彈性運動步驟:


1)、写两个速度公式;

2)、写两个停止条件:速度的绝对值<=1,距离[目標點-本身位置]的绝对值<=1;

3)、修正偏差:距離 == 目標點;速度 ==0

function sMove() {
        clearInterval(_t)
        _t = setInterval(function () {
//1、写两个速度公式
        _speed+=(500-div.offsetLeft)/6
        _speed*=0.75
//2、写两个停止条件 速度的绝对值,距离的绝对值
        if(Math.abs(_speed)<=1 && Math.abs(500-div.offsetLeft)<=1){
        clearInterval(_t)
//3/修正偏差
         div.style.left = '500px'
         _speed = 0;
        }
        else{
        div.style.left = div.offsetLeft+_speed+'px'
        }
    }, 30)
}



首先,滾動歌詞的效果
1、定認兩個div,定位重疊

<div id="div1"><span>红眼睛幽幽的看着这孤城,如同苦笑挤出的高兴,浮华盛世做分手布景</span></div>
<div id="div2"><span>红眼睛幽幽的看着这孤城,如同苦笑挤出的高兴,浮华盛世做分手布景</span></div>

2、第一個div1定住不動;div2外層限制寬高加overflow:hidden; div2內層span設置定位,限制高,寬2000px;

#div2{color:#cd0000;height:36px;width:36px;overflow:hidden;}
#div2 span{position:absolute;left:0;top:0;width:2000px;height:20px}

3、理解,div2外層向左移動+1px/每次時,內層span2同時相反移動

setInterval(function(){
   div2.style.left = div2.offsetLeft+1+'px';
   span2.style.left = -div2.offsetLeft+'px';
},30)

so,彈性菜單的例子是:

1、佈局:mark為需要在上面運動的項;

<ul id="ul1">
    <li id="mark">
        <ul>
            <li>首页</li>
            <li>论坛</li>
            <li>视频</li>
            <li>留言</li>
        </ul>
    </li>
    <li class="box">首页</li>
    <li class="box">论坛</li>
    <li class="box">视频</li>
    <li class="box">留言</li>
</ul>

See the Pen gaGVEL by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

当attr = width || height 時,低IE會出現彈性過過界,不允許負值,即出現錯誤; 所以
var H = div.offsetHeight + _speed;
if(H<0){  //ie下元素的高度不能为负值;
    H=0;
}

弹性运动整合版

function sMove(obj, json, fn) {
    clearInterval(obj.timer);
    var json2 = copy(json);
    obj.timer = setInterval(function () {
        var bStop = true;
        for (var attr in json) {
            var iCur = 0;
            if (attr == 'opacity') {
                iCur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
            } else {
                iCur = parseInt(getStyle(obj, attr));
            }
            json2[attr] += (json[attr] - iCur) / 6;
            json2[attr] *= 0.75;
            if (Math.abs(json2[attr]) < 1 && Math.abs(json[attr] - iCur) <= 1) {
                if (attr == 'opacity')
                {
                    obj.style.filter = 'alpha(opacity:' + (json[attr]) + ')';
                    obj.style.opacity = (json[attr]) / 100;
                }
                else
                {
                    obj.style[attr] = json[attr] + 'px';
                }
            } else {
                bStop = false;
                if (attr == 'opacity')
                {
                    obj.style.filter = 'alpha(opacity:' + (iCur + json2[attr]) + ')';
                    obj.style.opacity = (iCur + json2[attr]) / 100;
                }
                else
                {
                    obj.style[attr] = Math.round(iCur + json2[attr]) + 'px';
                }
            }
        }
        if (bStop) {
            clearInterval(obj.timer);
            fn && fn.call(obj)
        }
    }, 30);
};
function getStyle(obj, attr) {
    if (obj.currentStyle) {
        return obj.currentStyle[attr];
    } else {
        return getComputedStyle(obj, false) [attr];
    }
}
function copy(obj) {
    var o = {
    };
    for (var i in obj) {
        o[i] = 0;
    }
    return o;
}



碰撞运动,找到临界点,再确定运动方向,改对应的速度 ,將速度取反;

var _div = document.getElementById('div1')
var _speedX = 10;
var _speedY = 10;
sMove()
//碰撞运动,1、找到临界点,再确定运动方向,改对应的速度 (速度取反)
function sMove(){
setInterval(function () {
    var L = _div.offsetLeft +_speedX;
    var T = _div.offsetTop +_speedY;
    if(T>document.documentElement.clientHeight-_div.offsetHeight){
        T =document.documentElement.clientHeight-_div.offsetHeight
        _speedY *=-1
    }
    if(T<0){
        T=0;
        _speedY*=-1 //又变为正
    }
    if(L>document.documentElement.clientWidth-_div.offsetWidth){
        L =document.documentElement.clientWidth-_div.offsetWidth
        _speedX *=-1
    }
    if(L<0){
        L=0;
        _speedX*=-1 //又变为正
    }
    _div.style.left = L +'px'
    _div.style.top = T +'px'

},30)
}

自由落體運動、拋物線運動


自由落體: 只需改變top值,接觸到目標點後速度取反向上運動,再使用摩擦系數使速度停下來;

拋物線: 添加left方向速度及判定,摩擦系數使速度停下來,注意初始化目標位置及初始化速度;

See the Pen ojodqO by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

iphone拖動效果


首先,拖動

obj.onmousedown = function(e){
    var e = e || event;
    ....
    document.onmousemove = function(e){
        ...
    }
    document.onmouseup = function(e){
        document.onmousemove = document.onmouseup = null;
        ...
    }
    return false;
}

mousemove,鼠標移動的距離 == 元素left值移動的距離 ul1.style.left = e.clientX-disX + 'px'
mouseup時,元素需要移動的距離為一個li的距離,產生的效果由彈性公式生成;
當mousedown時存鼠標位置downX,與抬起時位置對比,小於走左,大於走右;
使用變量inow++ --

See the Pen KdyRrX by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

公告碰撞效果


See the Pen meqLgV by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

零JS筆記 | javascript運動 | 匀速 | 缓冲

運動基礎:勻速運動
運動框架實現:1、開始前,關閉已有定時器;2、檢測停止條件與執行運動對立;(if/else)

btn.onclick =function(){
    sMove()
}
function sMove(){
    clearInterval(_t)
    _t = setInterval(function () {
        if(div1.offsetLeft >= 500){
            clearInterval(_t)
        }
        else{
            div1.style.left = div1.offsetLeft+10+'px'
        }
    },30)
}

分享到:

See the Pen MavJVv by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

透明變化的問題 小數點精度問題:alert(0.1+0.2) //0.3000000000004 所以,操作須用整數; 透明度處理分IE及標準 ; 獲取透明度的值,不能直接使用obj.style.opacity,須使用
function css(obj,attr){
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj) [attr]
}

之後通過css()獲取透明度值再*100四舍五入轉整數;,所以是:

function sMove2(obj, _target, _speed) {
  clearInterval(_t)
  _t = setInterval(function () {
    var iCur = Math.round(css(obj, 'opacity') * 100)
    if (iCur == _target) {
      clearInterval(_t)
    } 
    else {
      obj.style.opacity = (iCur + _speed) / 100  //標準
      obj.style.filter = 'alpha(opacity=' + iCur + _speed + ')' //IE
    }
  }, 30)
}

使多物體能同時運動,技巧是更改定時器命名:obj._t 整合是:

function sMove2(obj, attr, _target, _speed) {
  clearInterval(obj._t)
  var iCur = 0;
  obj._t = setInterval(function () {
    if (attr == 'opacity') {                   //判斷是否透明
      iCur = Math.round(css(obj, attr) * 100)
    } 
    else {
      iCur = parseInt(css(obj, attr));
    }
    if (iCur == _target) {                    //判斷是否到結束點
      clearInterval(obj._t)
    } 
    else {                                   //未到結束點時
      if (attr == 'opacity') {                          //透明操作
        obj.style.opacity = (iCur + _speed) / 100
        obj.style.filter = 'alpha(opacity=' + iCur + _speed + ')'
      } 
      else {                                        //其他操作                
        obj.style[attr] = iCur + _speed + 'px'
      }
    }
  }, 30)
}
function css(obj, attr) {
  return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj) [attr]
}

使用多個值同時運動,比如,走width:200同時height:300; 所以獲取參數使用json,for in來操作

function sMove2(obj, json, _speed) {
  clearInterval(obj._t)
  var iCur = 0;
  obj._t = setInterval(function () {
    var on = true;
    //定時器每走一下,把要運動的屬性推進一次;
    for (var attr in json) {
      var _target = json[attr]
      if (attr == 'opacity') {
        iCur = Math.round(css(obj, attr) * 100)
      } 
      else {
        iCur = parseInt(css(obj, attr));
      }
      if (iCur !== _target) { //如果其中有一個屬性沒到,則on=false
        //什麼時候停定時器,所有屬性都運動到了
        on = false //記住這是寶時器,所有on的值在不斷改變,不存在駐內在需要變回true的情況,因為一開頭定義就是true;
        if (attr == 'opacity') {
          obj.style.opacity = (iCur + _speed) / 100
          obj.style.filter = 'alpha(opacity=' + iCur + _speed + ')'
        } 
        else {
          obj.style[attr] = iCur + _speed + 'px'
        }
      }
    }
    //注意要在for in外面看是否所有屬性都運動到了。

    if (on) {
      clearInterval(obj._t)
    }
  }, 30)
}

把運動使用.call()回調加上,即可在回調裏使用this

if (on) {
  clearInterval(obj._t)
  fn && fn.call(obj) //this指向,默認是window,所以指向調用的obj
}



缓冲运动,關鍵,速度怎麼算?

缓冲运动 与摩擦力的区别:可以精确的停到指定目标点 距离越远速度越大 速度由距离决定 速度=(目标值-当前值)/缩放系数 Bug:速度取整 值取整
//當速度小於0.5時,掛了。
console.log(div1.offsetLeft);
_speed = (500 - div1.offsetLeft) * 0.2

//所以需要的_speed小於0.5時,向上取整為1; 
_speed = _speed > 0 ? Math.ceil(_speed)  : Math.floor(_speed)

注意: css可以解析小數點,js會把當前值四舍五入運算;

所以整合是,速度參數不需要,因為算出來即可;

function sMove2(obj, json, fn) {
    clearInterval(obj._t);
    var iCur = 0;
    var _speed = 0;
    obj._t = setInterval(function() {
        var on = true;
        for ( var attr in json ) {
            var _target = json[attr];
            if (attr == 'opacity') { //opacity属性传值为0 - 100
                iCur = Math.round(css( obj, 'opacity' ) * 100);
            } else {
                iCur = parseInt(css(obj, attr));
            }
            _speed = ( _target - iCur ) / 8;
            _speed = _speed > 0 ? Math.ceil(_speed) : Math.floor(_speed);
            if (iCur != _target) {
                on = false;
                if (attr == 'opacity') {
                    obj.style.opacity = (iCur + _speed) / 100;
                    obj.style.filter = 'alpha(opacity='+ (iCur + _speed) +')';
                } else {
                    obj.style[attr] = iCur + _speed + 'px';
                }
            }
        }
        if (on) {
            clearInterval(obj._t);
            fn && fn.call(obj);
        }
    }, 30);
}

function css(obj, attr) {
    return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj) [attr]
}

下面是實例,多圖片殿開收縮:1、元素居中放大,寬高、定位都要改變,圖片放大1倍,則位移放大寬高的一半;

2、用js設置css樣式時,須注意問題,在同一個代碼塊中,有些css樣式的設置的權限要高於其他的樣式;解決:可放在不同代碼塊裏;

See the Pen PPKWLZ by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

帶運動的留言本、注意ul及li加overflow:hidden;否則運動會有問題;

_li.style.height = 0;
_li.style.opacity = 0; //因為要運動。所以先初始化為0;

See the Pen RWZKmw by elmok (@elmok) on CodePen.


<script async src="//assets.codepen.io/assets/embed/ei.js"></script>

返回頂部:如果是fixed定位則不需要算setTop值;使用absolute固定在右下角,須一直改變top值
setTop()方法,當前的style.top = 當前視口高度 + 滾動條 - 元素本身高度
iCur表示當前變化的值:Math.floor((0 - iCur) / 8);當前變化的值到頂部0 來計算出speed
iCur== 0,到頂部了,清除,未到頂部,則滾動條高度:document.documentElement.scrollTop = document.body.scrollTop = iCur + _speed;

var div = document.getElementById('div1')
var _t = null;
var b = 1;
setTop();
window.onscroll = function () {
  if (b != 1) { //如果==1,那麼當前scroll事件是被定時器所觸發的,所果不等於1,即非定時器的其他任何一個操作觸發
    clearInterval(_t)
  }
  b = 2;
  setTop();
}
div.onclick = function () {
  clearInterval(_t)
  var iCur = _speed = 0;
  _t = setInterval(function () {
    iCur = document.documentElement.scrollTop || document.body.scrollTop
    _speed = Math.floor((0 - iCur) / 8); //其實還是算speed
    if (iCur == 0) {
      clearInterval(_t)
    } else {
      document.documentElement.scrollTop = document.body.scrollTop = iCur + _speed;
    }
    b = 1;
  }, 30)
}
function setTop() {
  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  div.style.top = scrollTop + document.documentElement.clientHeight - div.offsetHeight + 'px'
}

圖片預加載


當給Image()對象的src屬性一個url時,則對象去加載,加載完成保存在瀏覽器的cache裏,下次若再用,則直接從cache文件讀取;所以速度很快 ,並且節約資源;使用Image()對像,把需要的圖片地址處理後預加載到瀏覽器中;在頁面上再調用相同地址時,瀏覽器會自動先從cache裏讀取;

兩個事件:onload 當資源加載完成時,onerror,當資源加載失敗時

var oImage = new Image()  //對象
var img = document.getElementById('img')  //頁面元素
oImage.src = 'http://i1.download.fd.pchome.net/1.jpg'  //對象加載
oImage.onload = function () {
  document.onclick = function () {
    img.src = 'http://i1.download.fd.pchome.net/1.jpg'   //頁面請求
  }
}
function xl() {
  oimg.src = arr[icur]  //頁面上的圖片用數組先存起
  oimg.onload = function () {
    icur++
    if (icur < arr.length) { //如果小於,證明未下載完,則再次調用xl()
      xl() //遞歸
    }
    document.title = icur + '/' + arr.length;
  }
}

按需加載


初始化時:

 <img _src="t5.JPG" src="white.png" alt=""/>

當obj的top值 < 滾動條 + 視口高度;把_src的值附給src;
避免重覆加載,可以在賦值後的img上加自定義屬性 _img[i].isload = true; 如果isload =false則加載,=true則不重覆加載

window.onload = function () {
  var _ul = document.getElementById('ul1')
  var _img = _ul.getElementsByTagName('img')
  showImage()
  window.onscroll = function () {
    showImage()
  }
  function showImage() {
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop
    for (var i = 0; i < _img.length; i++) {
    //注意前後順序
      if (!_img[i].isload && getTop(_img[i]) < scrollTop + document.documentElement.clientHeight) {
        _img[i].src = _img[i].getAttribute('_src')
        _img[i].isload = true; //這種方法並非最優,for循環還要跑
      }
    }
  }
  function getTop(obj) {
    var itop = 0;
    while (obj) {
      itop += obj.offsetTop;
      obj = obj.offsetParent;
    }
    return itop;
  }
}

零JS筆記 | 正則基礎

部分常用正則:

//QQ驗證:
var re = /^[1-9]\d{4,11}$/

//去空格:
var re = /^\s+|\s+$/g;

//匹配中文:
[\u4e00-\u9fa5]

//行首行尾空格
^\s*|\s*$

//Email:
^\w+@[a-z0-9]+(\.[a-z]+){1,3}$

//网址:
[a-zA-z]+://[^\s]*

//QQ号:
[1-9][0-9]{4,9}

//邮政编码:
[1-9]\d{5}

//身份证:
[1-9]\d{14}|[1-9]\d{17}|[1-9]\d{16}x

ver re = {
    qq:[1-9][0-9]{4,9},
    email:^\w+@[a-z0-9]+(\.[a-z]+){1,3}$,
    number:/\d+/,
    url:[a-zA-z]+://[^\s]*,
    nospace:^\s*|\s*$,
    postalcode:[1-9]\d{5},
    icard:[1-9]\d{14}|[1-9]\d{17}|[1-9]\d{16}x
}

re.email




例如分析:

abcd12@163qq.com

^w+@[a-z0-9]+(.[a-z]+){1,3}$

^w+ :可出現多位字符

@:匹配@

[a-z0-9]+ :可出現多次字符

(.[a-z]+) :分組,.匹配真正的. [a-z]:出現net com 一個整體;

{1,3}$: 再+量詞表示如.com.cn .cn.net等等


普通查看字符串裏的數字

str = 'weirup123skjdlj890lkjd12kldk899'
console.log(findNum(str));
function findNum(str) {
  var arr = [
  ]
  var tmp = ''
  for (var i = 0; i < str.length; i++) {
    if (str.charAt(i) <= '9' && str.charAt(i) >= '0') {
      //  arr.push(str.charAt(i))
      tmp += str.charAt(i)
    } 
    else {
      if (tmp) {
        arr.push(tmp);
        tmp = '';
      }
    }
  }
  if (tmp) {
    arr.push(tmp)
    tmp = '';
  }
  return arr;
}
var re = /\d+/g; //找出數字;
var re = /\D+/g; //找出字母;
console.log(str.match(re));

<style>
.reg-tb{

width:100%;border-collapse: collapse

}
.reg-tb td{border:1px solid #ccc;padding:5px;}
.reg-tb tr>td:first-child{min-width: 100px;

text-align: center;}

</style>

test 匹配返回真假 寫法:re.test(str)
search 成功返回位置,匹配失败,就返回-1,像indexOf 寫法:str.search(re)
replace 返回替换后的字符串 寫法:str.replace(re,newstr),replace : 第二个参数;可以是字符串,也可以是一个回调函数
match 返回匹配数组 寫法:str.search(re)

轉義字符:

n 換行
r 製表
t 回車
s 空格
S 非空格
d 數字
D 非數字
w 字符 (字母、數字、下劃線_)
W 非字符 (特殊字符、漢字等)
b 独立的部分(起始、结束、空格)
B 非独立的部分

小記錄

i i——ignore 正则中的默认:是区分大小写; 如果不区分大小写的话,在正则的最后加标识 i (不区分大小写)
g 全局匹配:g——global;正则默认:正则匹配成功就会结束,不会继续匹配 如果想全部查找,就要加标识 g(全局匹配)
+ 量詞;匹配不确定的位置 + : 至少出现一次,如d+,即至少匹配多次數字,如果連接數字則為一個整體
{} 量詞;不確定次數:{4,7}:最少出現4次,最多出現7次;{4,}最少出現4次;{4}:剛好出現4次;var re = /ddd/; === /d{3}/;
+ = {1,}
? ? 重複零次或1次;var re = /a?/,表示a只能重複0次或1次
? = {0,1}
* 前边的内容可以重复任意次以使整个表达式得到匹配。因此,.连在一起就意味着任意数量的不包含换行的字符
* = {0,},即可以不出現,但+是一定要出現一次
| “或”的意思,正則內使用,var re = /a|b/;
() 匹配子項,把正则的整体叫parent,左边第一个小括号里面的正则,叫做这个第一个子项...var re = /(a)(b)(c)/;
[] 用中括号表示,中括号的整体代表一个字符; var str = 'abc',var re = /a[dec]c/;,第1位匹配a,第2位匹配[dec]中的一位,第3位匹配c,則返回true
^ 1、排除 : ^ 如果^写在[]里面的话,就代表排除的意思,如var re = /a1c/;,第2位只要不是bde返回true
2、匹配字符串開頭;如var re= /^d/,開頭必須為數字;
$ $匹配结尾; ^和$的意义就变成了匹配行的开始处和结束处。比如填寫QQ號碼必須為5位-12位, var re = /^d{5,12}$/ {5,12}$表示結束的位置必須是數字
- 如果-写在[]里面的话,就代表范围,范围一定是从小到大的,var re = /a[b-k]c/; [a-z] [0-9] [A-Z]、[a-z0-9A-Z];
var str = 'abc'
var re = /a[a-z]c/
console.log(re.test(str))  //,一共3位,對應上所以是true

//如果str = 'abcd',只會對應前3位,對應不是,所以是false
所以,如果需要多個匹配,+表示[a-z]有多位,可以中間一直匹配,當無法匹配時,再找最後一位匹配

var str = 'abcsdfsdfsdfsdfsdfsdfsf'
var re = re = /a[a-z]+c/ 
console.log(re.test(str))   //true

//所以,過濾html標籤正則是:

var re = /<[^>]+>/g; 
str.replace(re, '');  //應用正則替換為空

</td>
</tr>
<tr>

<td>.</td>
<td>正則中 . 表示任意字符,而匹配真正的點:\.   與一般相反</td>

</tr>

<tr>

<td>\1、 \2、\3</td>
<td>重複的第1、2、3個子項[配合()]; 如/(a)(b)(c)\1/===/(a)(b)(c)a/;表示兩個要完全相同,應用比如匹配p標籤配對</td>

</tr>

</table>

test();

var str = 'abcdef';
var re1 = /b/;
var re2 = /w/;
var re3 = /bc/;
var re4 = /bd/;
alert(re1.test(str)); //true
alert(re2.test(str)); //false
alert(re3.test(str)); //true
alert(re4.test(str)); //false
var str = '473t9487306';
var re = /\D/;
if (re.test(str)) {
  alert('不全是数字');
} else {
  alert('全是数字');
}



search :字符串.search(正则)

var str = 'abcdef';
var re1 = /bcd/;
var re2 = /w/;
var re3 = /B/;
var re4 = /B/i;
var re5 = new RegExp('B', 'i'); //这一行的写法与上面一行的写法,意义完全一样
alert(str.search(re1)); //弹出1 弹的是匹配的首字母的位置
alert(str.search(re2)); //弹出-1
alert(str.search(re3)); //弹出-1 //正则默认下是区分大小写的
alert(str.search(re4)); //弹出1
alert(str.search(re5)); //弹出1



match :返回数组
/d+/g; //这里说明前面的反斜杠d至少出现一次,多则不限

var str = 'sdogh3woiehgxfkjb789paf34dj4pgdfhgdorg43';
var re1 = /\d/;
var re2 = /\d/g;
var re3 = /\d\d/g;
var re4 = /\d\d\d/g;
var re5 = /\d\d\d\d/g;
var re6 = /\d+/g; //这里说明前面的反斜杠d至少出现一次,多则不限
alert(str.match(re1)); //[3] 返回的是找到的第一个数字
alert(str.match(re2)); // [3, 7, 8, 9, 3, 4, 4, 4, 3]
alert(str.match(re3)); //[78, 34, 43]
alert(str.match(re4)); //[789]
alert(str.match(re5)); // null
alert(str.match(re6)); //[3, 789, 34, 4, 43]

replace: 替換所有匹配:

返回替换后的字符串

字符串.replace(正则,想替换的)

例子:敏感词过滤

匹配子项

例子:日期格式化

replace的写法 : 字符串.replace(正则, 新的字符串)

var str1 = 'aaa';
var str2 = 'aaa';
var str3 = 'aaa';
var re1 = /a/;
var re2 = /a/g;
var re3 = /a+/g;
str1 = str1.replace(re1, 'b');
alert(str1); //'baa'
str2 = str2.replace(re2, 'b');
alert(str2); //'bbb'
str3 = str3.replace(re3, 'b');
alert(str3); //'b'            特別留意此處;所有匹配到的都換成b,a+表示匹配多個a,如果匹配到,則替換成b

函数的第一个参数:就是匹配成功的字符,每次匹配到的字符不同,不同長度返回不同*號

aT[1].value = aT[0].value.replace(re, function (str) { //函数的第一个参数:就是匹配成功的字符
  //alert(str);
  var result = '';
  for (var i = 0; i < str.length; i++) {
    result += '*';
  }
  return result;
});

匹配子项

// 匹配子项 : 小括号 () (还有另外一个意思:分组操作)
//把正则的整体叫做(母亲)
// 然后把左边第一个小括号里面的正则,叫做这个第一个子项(母亲的第一个孩子)
// 第二个小括号就是第二个孩子
var str1 = '2013-6-7';
var str2 = '2013-6-7';
var str3 = '2013-6-7';
var str4 = '2013-6-7';
var str5 = '2013-6-7';
var re1 = /\d+-/g;  //+匹配d
var re2 = /\d-+/g; //一个数字加至少一个横杠   +匹配d-
var re3 = /(\d-)+/g;
var re4 = /(\d+)(-)/g;
var re5 = /(\d+)(-)/g;
// str1.replace(re1, function($0){
//  alert($0); //2013- 和 6-
// })
// str2.replace(re2, function($0){
//  alert($0); //3- 和 6-
// })
// str3.replace(re3, function($0){
//  alert($0); //3-6-
// })
/*
        str4.replace(re4, function($0, $1, $2){
            // 第一个参数 : $0 (母亲)       /(\d+)(-)/g;
            // 第二个参数 : $1 (第一个孩子)  (\d+)
            // 第三个参数 : $2 (第二个孩子)  (-)
            // 以此类推
            alert($0); //2013- , 6-
            alert($1); //2013 , 6
            alert($2); // - , -
            //运行一次弹出:2013-, 2013, -, 6-, 6, -
        })
        */
str5 = str5.replace(re5, function ($0, $1, $2) {
  // return $0.substring(0, $0.length - 1) + '.';
  return $1 + '.'; //2013.6.7
})
alert(str5); //2013.6.7

match方法中的匹配子项

var str1 = 'abc';
var re1 = /abc/;
var str2 = 'abc';
var re2 = /(a)(b)(c)/;
var str3 = 'abc';
var re3 = /(a)(b)(c)/g;
alert(str1.match(re1)); //[abc]
alert(str2.match(re2)); //[abc, a, b, c](当match不加g的时候才可以获取到匹配子项的集合)
alert(str3.match(re3)); //[abc] //这里因为re里面加个g,就不会获得上面那一句的结果了

正則表達式字符類

[abc]

例子:o[usb]t——obt、ost、out

字符类 : 一组相似的元素或字符

//字符类 : 用中括号表示,中括号的整体代表一个字符

//字符类 : 一组相似的元素或字符
//字符类 : 用中括号表示,中括号的整体代表一个字符

var str1 = 'abc';
var re1 = /a[bde]c/;
alert(re1.test(str1)); //true
var str2 = 'aec';
var re2 = /a[bde]c/;
alert(re2.test(str2)); //true
var str3 = 'abdc';
var re3 = /a[bde]c/;
alert(re3.test(str3)); //false

//排除 : ^ 如果^写在[]里面的话,就代表排除的意思
var str4 = 'abc';
var re4 = /a[^bde]c/;
alert(re4.test(str4)); //false
var str5 = 'awc';
var re5 = /a[^bde]c/;
alert(re5.test(str5)); //true

//范围 : - 如果-写在[]里面的话,就代表范围,范围一定是从小到大的
var str6 = 'abc';
var re6 = /a[e-j]c/;
alert(re6.test(str6)); //false
var str7 = 'afc';
var re7 = /a[e-j]c/;
alert(re7.test(str7)); //true
var str8 = 'a3c';
var re8 = /a[a-z0-9A-Z]c/;
alert(re8.test(str8)); //true
var str9 = 'a3eJ86Xc';

var re9 = /a[a-z0-9A-Z]+c/; //在中括号外面添加了+,代表可以多位
alert(re9.test(str9)); //true

字符类实例,过滤标签

        var str1 = 'a你c';
        var re1 = /a.c/;

        alert(re1.test(str1)); //true

        var str2 = 'a你c';
        var re2 = /a\.c/;
        alert(re2.test(str2)); //false

        // \b : 独立的部分(起始、结束、空格)
        // \B : 非独立的部分

        var str3 = 'onetwo';
        var re3 = /one/;
        alert(re3.test(str3)); //true;

        var str4 = 'onetwo';
        var re4 = /\bone/; //代表字母o前面必须是独立部分,o前面是起始位置
        alert(re4.test(str4)); //true;

        var str5 = 'onetwo';
        var re5 = /one\b/; //e后面是个t,不是个独立部分
        alert(re5.test(str5)); //false; 

        var str6 = 'one two';
        var re6 = /one\b/; //e后面是个空格,是独立部分
        alert(re6.test(str6)); //true;

        var str7 = 'onetwo';
        var re7 = /\bone\b/; //前面满足后面不满足,整体也就不满足
        alert(re7.test(str7)); //false;

当正则需要传参时,一定要用全称的写法,如var re = new RegExp('\b'+sClass+'\b'),這裏也一定要雙\,字符串當中特殊的字符想輸入,必須再加,如輸出單引號'

var str = 'sddfdsfdsfdsfdsfdddddd'
//先排在一起
var arr = str.split('')
str = arr.sort().join('')
var value = ''
var index = 0;
var re = /(\w)\1+/g;
str.replace(re, function (_0,_1) {
    console.log(_0);
console.log('_1'+_1);
if(index<_0.length){
    index = _0.length;
    value = _1;
}
console.log('最多的字符為:' + value + '出現次數為:' + index);
})

前項聲明,反前項聲明

        var s =  'abacad'
        var re = /a(?=b)/g;    //匹配 ab,但只替換匹配到的ab中的a,b不替換;
        s =  s.replace(re,'*')
        console.log(s);  //*bacad
        var s =  'abacad'
        var re = /a(?!b)/g;    //匹配 ab,a後面不能匹配到b,其他可以匹配
        s =  s.replace(re,'*')
        console.log(s);  //ab*c*d

所以,過濾html標籤,但保留li標籤: re = /<2+>/g;


  1. bde
  2. >?!li

零JS筆記 | Ajax-跨域-百度提示-豆瓣

解決跨域問題:服务器代理或jsonp

1、script標籤;
2、在資料加載進來之前,定義好一個fn,fn接收一個參數,fn裏再拿數據;然後需要時通過script標籤加載對應的遠程文件資源,當遠程文件資源被加載時會執行前面定義好的fn,並且把數據當fn參數傳入;
如:1.txt内容为:

fn([1,2,3])

然后在html开头使用script定义fn,一定要放前面,如放window.onload 里,需使用window.fn(){..}这样调用

function fn(data) {
    alert(data)
}

之后下面window.onload

window.onload = function () {
    var btn = document.getElementById('btn')
    btn.onclick = function () {
        //当按钮点击时再去加载远程资源,让他执行;
        var _script = document.createElement('script')
        _script.src = '1.txt'
        document.body.appendChild(_script)
    }
}
因此,操作别的网站的json数据,主要是能够找到调用的命我空间,即,可以有callback=fn的函数



调用接口实现百度下拉提示:

1)、找到接口,http://suggestion.baidu.com/su?wd=keyword&cb=elmok及调用命名,如elmok即我们可以使用的函数名;

2)、使用实时创建script标签

var _script = document.createElement('script')
_script.src = "http://suggestion.baidu.com/su?wd="+this.value+"&cb=elmok"
document.body.appendChild(_script)

3)、开头创建elmok函数使用数据;

function elmok(data){
    var _ul = document.getElementById('ul1')
    var html =''
    if(data.s.length){  //如果得到数据的长度不为0
        _ul.style.display = 'block'
        for(var i=0;i<data.s.length;i++){
            html+='<li><a target="_blank" href="https://www.baidu.com/s?&wd='+data.s[i]+'">'+data.s[i]+'</a></li>'
        }
        _ul.innerHTML = html;
    }
}

得到的数据如图:
可看到 data.s[i]即为数组,可以循环这个数据输出显示为提示内容;
运行



豆瓣搜索接口:

1)、找到接口callback名:http://api.douban.com/book/subjects?q=keyword&alt=xd&callback=elmok

2)、使用script标签创建

btn.onclick = function () {
    if(_q.value !=''){
        var _script = document.createElement('script')
        _script.src = "http://api.douban.com/book/subjects?q="+_q.value+"&alt=xd&callback=elmok"
        document.body.appendChild(_script)
    }
}

2)、开头创建elmok函数使用数据

function elmok(data){
    var msg = document.getElementById('msg')
    var _list = document.getElementById('list')
    msg.innerHTML = data.title.$t + ':'+data['opensearch:totalResults'].$t
    var _entry = data.entry;
    var html = ''
    for(var i=0;i<_entry.length;i++){
        html+='<dl><dt>'+_entry[i].title.$t+'</dt><dd><img src='+_entry[i].link[2]['@href']+' /></dd>'
    }
    _list.innerHTML = html
}


運行

© 2025 J.chongj.chong@qq.com 模板由cho制作.