js封装简单实例源码记录

Posted 明留

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js封装简单实例源码记录相关的知识,希望对你有一定的参考价值。

1、运动封装:doMove ( obj, attr, dir, target, endFn )  加入回调、&&、||用法注释

<script>
var oBtn1 = document.getElementById(\'btn1\');
var oDiv = document.getElementById(\'div1\');

oBtn1.onclick = function () {
    
    // doMove ( oDiv, \'width\', 34, 600 );
    doMove ( oDiv, \'left\', 12, 900, function () {
        doMove ( oDiv, \'top\', 34, 500 );
    });

};

function doMove ( obj, attr, dir, target, endFn ) {
    
    dir = parseInt(getStyle( obj, attr )) < target ? dir : -dir;
    
    clearInterval( obj.timer );
    
    obj.timer = setInterval(function () {
        
        var speed = parseInt(getStyle( obj, attr )) + dir;            // 步长
        
        if ( speed > target && dir > 0 ||  speed < target && dir < 0  ) {
            speed = target;
        }
        
        obj.style[attr] = speed + \'px\';
        
        if ( speed == target ) {
            clearInterval( obj.timer );
            
            /*
            if ( endFn ) {
                endFn();
            }
            */
            endFn && endFn();  //只有endFn条件为真就会执行endFn()
            //alert(getStyle(obj, \'left\')||3);     //哪边为true就返回哪边  布尔、string、number、object、function
        }
        
    }, 30);
}

function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; }
</script><script>
var oBtn1 = document.getElementById(\'btn1\');
var oDiv = document.getElementById(\'div1\');

oBtn1.onclick = function () {
    
    // doMove ( oDiv, \'width\', 34, 600 );
    doMove ( oDiv, \'left\', 12, 900, function () {
        doMove ( oDiv, \'top\', 34, 500 );
    });

};

function doMove ( obj, attr, dir, target, endFn ) {
    
    dir = parseInt(getStyle( obj, attr )) < target ? dir : -dir;
    
    clearInterval( obj.timer );
    
    obj.timer = setInterval(function () {
        
        var speed = parseInt(getStyle( obj, attr )) + dir;            // 步长
        
        if ( speed > target && dir > 0 ||  speed < target && dir < 0  ) {
            speed = target;
        }
        
        obj.style[attr] = speed + \'px\';
        
        if ( speed == target ) {
            clearInterval( obj.timer );
            
            /*
            if ( endFn ) {
                endFn();
            }
            */
            endFn && endFn();  //只有endFn条件为真就会执行endFn()
            //alert(getStyle(obj, \'left\')||3);     //哪边为true就返回哪边  布尔、string、number、object、function
        }
        
    }, 30);
}

function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; }
</script>
通用动画js

 2、ajax封装

function ajax(method, url, data, success) {
    var xhr = null;
    try {
        xhr = new XMLHttpRequest();
    } catch (e) {
        xhr = new ActiveXObject(\'Microsoft.XMLHTTP\');
    }
    
    if (method == \'get\' && data) {
        url += \'?\' + encodeURI(data);
    }
    
    xhr.open(method,url,true);
    if (method == \'get\') {
        xhr.send();
    } else {
        xhr.setRequestHeader(\'content-type\', \'application/x-www-form-urlencoded\');
        xhr.send(data);
    }
    
    xhr.onreadystatechange = function() {
        
        if ( xhr.readyState == 4 ) {
            if ( xhr.status == 200 ) {
                success && success(xhr.responseText);   //定义回调,并传入参数,客户端接收这个参数,并显示出来
            } else {
                alert(\'出错了,Err:\' + xhr.status);
            }
        }
        
    }
}
ajax封装

 //最好将监听放在open、send方法前面调用。xhr.onreadystatechange=function(){...};

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script src="ajax.js"></script>
<script>
window.onload = function() {
    
    var oBtn = document.getElementById(\'btn\');
    
    
    oBtn.onclick = function() {
        
        /*ajax({
            url    :    \'getNews.php\',
            success : function(data) {
                //...
            }
        });*/
        
        ajax(\'get\',\'getNews.php\',\'\',function(data) {
            var data = JSON.parse( data );
                
            var oUl = document.getElementById(\'ul1\');
            var html = \'\';
            for (var i=0; i<data.length; i++) {
                html += \'<li><a href="">\'+data[i].title+\'</a> [<span>\'+data[i].date+\'</span>]</li>\';
            }
            oUl.innerHTML = html;
        });
        
        setInterval(function() {
            ajax(\'get\',\'getNews.php\',\'\',function(data) {
                var data = JSON.parse( data );
                    
                var oUl = document.getElementById(\'ul1\');
                var html = \'\';
                for (var i=0; i<data.length; i++) {
                    html += \'<li><a href="">\'+data[i].title+\'</a> [<span>\'+data[i].date+\'</span>]</li>\';
                }
                oUl.innerHTML = html;
            });
        }, 1000);
        
    }
}
</script>
</head>

<body>
    <input type="button" value="按钮" id="btn" />
    <ul id="ul1"></ul>
</body>
</html>
定时刷新

 3、定宽瀑布流

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
body {margin: 0;}
#ul1 {width: 1080px; margin: 100px auto 0;}
li { width: 247px; list-style: none; float: left; margin-right: 10px; }
li div {border: 1px solid #000; padding: 10px; margin-bottom: 10px;}
li div img { width: 225px; display: block;}
</style>
<script src="ajax.js"></script>
<script>
window.onload = function() {
    var oUL=document.getElementById(\'ul1\');
    var aLi=oUL.getElementsByTagName(\'li\');
    var iPage=1;
    var b = true;
    
    getList();
    
    function getList() {
        
        ajax(\'get\', \'getPics.php\', \'cPage=\'+iPage, function(data){
             
             var data=JSON.parse(data);
             
             if ( !data.length ) {
                //后续没有数据了
                return ;
             }
            
             for(var i=0; i<data.length; i++) {
                   //获取高度最短的li
                    var _index = getShort();
                    
                    //创建3个节点div/img/p
                    var oDiv = document.createElement(\'div\');
                    var oImg = document.createElement(\'img\');
                    var oP = document.createElement(\'p\');
                    oImg.src = data[i].preview;
                    oImg.style.width = \'225px\';// 同比例缩放
                    oImg.style.height =  data[i].height * ( 225 / data[i].width ) + \'px\';
                    oDiv.appendChild( oImg );                
                    oP.innerHTML = data[i].title;
                    oDiv.appendChild( oP );
                    //最后节点永远放在高度最小的那列
                    aLi[_index].appendChild( oDiv );
             } 
             b=true;     
        });
    }
    
    
    window.onscroll = function() {
        var _index = getShort();
        var oLi = aLi[_index];
        
        var scrollTop=document.body.scrollTop||document.documentElement.scrollTop;
            
        if(getTop( oLi ) + oLi.offsetHeight < document.documentElement.clientHeight + scrollTop) {
             if(b) {
                  b=false;
                  iPage++;
                  getList();    
             }
        }
        
    };
    
    function getShort(){
        var index=0;
        var s=aLi[index].offsetHeight;
        for(var i=0; i<aLi.length; i++) {
            if(s>aLi[i].offsetHeight) {
                index=i;
                s=aLi[i].offsetHeight;             
            }
        }
        return index;
    }
     
    //最小的高度obj的top值 
    function getTop(obj) {
        var iTop = 0;
        while(obj) {
            iTop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        return iTop;    
    }
    
};
</script>
</head>

<body>
    <ul id="ul1">
        <li></li>
          <li></li>
        <li></li>
        <li></li>
    </ul>
</body>
</html>
ajax定宽瀑布流

4、ajax留言(调用后台) 

另外跨域域名下加\'Access-Control-Allow-Origin\' \'http://www.a.com\'; //这是允许访问该资源的域(服务器设置响应头信息,标准支持,ie不支持)

jsonp解决跨域

//ie支持此种跨域,标准不支持
  var oXDomainRequest = new XDomainRequest();
  oXDomainRequest.onload = function() {
   alert(this.responseText);
  }
  oXDomainRequest.open(\'get\', \'http://www.b.com/ajax.php\', true);
  oXDomainRequest.send();

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 300px; height: 30px; border: 1px solid #000; position: relative;}
#div2 {width: 0; height: 30px; background: #CCC;}
#div3 {width: 300px; height: 30px; line-height: 30px; text-align: center; position: absolute; left: 0; top: 0;}
</style>
<script>
window.onload = function() {
    
    var oBtn = document.getElementById(\'btn\');
    var oMyFile = document.getElementById(\'myFile\');
    var oDiv1 = document.getElementById(\'div1\');
    var oDiv2 = document.getElementById(\'div2\');
    var oDiv3 = document.getElementById(\'div3\');
    
    oBtn.onclick = function() {
        
        //alert(oMyFile.value);    //获取到的是file控件的value值,这个内容是显示给你看的文字,不是我们选择的文件
        
        //oMyFile.files file控件中选择的文件列表对象
        //alert(oMyFile.files);
        
        //我们是要通过ajax把oMyFile.files[0]数据发送给后端
        
        /*for (var attr in oMyFile.files[0]) {
            console.log( attr + \' : \' + oMyFile.files[0][attr] );
        }*/
        
        var xhr = new XMLHttpRequest();
        
        //
        xhr.onload = function() {
            //alert(1);
            //var d = JSON.parse(this.responseText);
            
            //alert(d.msg + \' : \' + d.url);
            
            alert(\'OK,上传完成\');
        }
        
        //获得ajax上传对象upload。
        var oUpload = xhr.upload;
        oUpload.onprogress  = function(ev) {
            //console.log(ev.total + \' : \' + ev.loaded);
            //上传比例,loaded 已经上传大小,  total总大小            
            var iScale = ev.loaded / ev.total;            
            oDiv2.style.width = 300 * iScale + \'px\';
            oDiv3.innerHTML = Math.floor(iScale * 100) + \'%\';
            
        }
        //上传一般都用post上传
        xhr.open(\'post\', \'post_file.php\', true);
        //设置发送文件的请求头
        xhr.setRequestHeader(\'X-Request-With\', \'XMLHttpRequest;\');        
        var oFormData = new FormData();    //通过FormData来构建提交数据
        oFormData.append(\'file\', oMyFile.files[0]);
        xhr.send(oFormData);
        
        
    }
    
}
</script>
</head>

<body>
    <input type="file" id="myFile" /><input type="button" id="btn" value="上传" />
    <div id="div1">
        <div id="div2"></div>
        <div id="div3">0%</div>
    </div>
<form action="pp_files.php" method="post" enctype="multipart/form-data">
<!--enctype:multipart/form-data 发送文件头--->
</form>
</body>
</html>
ajax上传文件
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>留言本</title>
    <link rel="stylesheet" href="css.css" type="text/css" />
    <script src="ajax.js"></script>
    <script src="guestbook.js"></script>
</head>

<body>
    <div id="header"></div>

    <div id="container">

        <div id="list"> 
        <!--<dl>
                <dt>
                    <strong>zmouse</strong> 说 :
                </dt>
                <dd>内容</dd>
                <dd class="t">
                    <a href="javascript:;" id="support">顶(<span>0</span>)</a>
                     | 
                    <a href="javascript:;" id="oppose">踩(<span>0</span>)</a>
                </dd>
            </dl>-->
        </div>
        <div id="showMore">显示更多...</div>

        <div id="sidebar">
        
            <div id="user" style="margin-bottom: 10px;">
                <h4><span id="userinfo"></span> <a href="" id="logout">退出</a></h4>
            </div>
        
            <!-- 注册 -->
            <div id="reg">
                <h4>注册</h4>
                <div>
                    <p>用户名:<input type="text" name="username" id="username1"></p>
                    <p id="verifyUserNameMsg"></p>
                    <p>密码:<input type="password" name="password" id="password1"></p>
                    <p><input type="button" value="注册" id="btnReg" /></p>
                </div>
            </div>

            <!-- 登陆 -->
            <div id="login">
                <h4>登陆</h4>
                <div>
                    <p>用户名:<input type="text" name="username2" id="username2"></p>
                    <p>密码:<input type="password" name="password2" id="password2"></p>
                    <p><input type="button" value="登陆" id="btnLogin" /></p>
                </div>
            </div>
            
            <!-- 留言发表 -->
            <div id="sendBox">
                <h4>发表留言</h4>
                <div>
                    <textarea id="content"></textarea>
                    <input type="button" value="提交" class="btn1" id="btnPost" />
                </div>
            </div>
        </div>

    </div>
    
</body>
</html>
留言HTML
window.onload = function() {
    
    var oUser = document.getElementById(\'user\');
    var oReg = document.getElementById(\'reg\');
    var oLogin = document.getElementById(\'login\');
    var oUserInfo = document.getElementById(\'userinfo\');
    var oList = document.getElementById(\'list\');
    var iPage = 1;
    
    var oShowMore = document.getElementById(\'showMore\');
    
    var oUsername1 = document.getElementById(\'username1\');
    var oVerifyUserNameMsg = document.getElementById(\'verifyUserNameMsg\');
    
    //初始化
    updateUserStatus();
    
    function updateUserStatus() {
        var uid = getCookie(\'uid\');
        var username = getCookie(\'username\');
        if (uid) {
            //如果是登陆状态
            oUser.style.display = \'block\';
            oUserInfo.innerHTML = username;
            oReg.style.display = \'none\';
            oLogin.style.display = \'none\';
        } else {
            oUser.style.display = \'none\';
            oUserInfo.innerHTML = \'\';
            oReg.style.display = \'block\';
            oLogin.style.display = \'block\';
        }
    }
    
    showList();
    
    /*
    验证用户名
    get
        guestbook/index.php
            m : index
            a : verifyUserName
            username : 要验证的用户名
        返回
            {
                code : 返回的信息代码 0 = 没有错误,1 = 有错误
                message : 返回的信息 具体返回信息
            }
    */
    oUsername1.onblur = function() {
        ajax(\'get\', \'guestbook/index.php\', \'m=index&a=verifyUserName&username=\' + this.value, function(data) {
            //alert(data);
            var d = JSON.parse(data);
            
            oVerifyUserNameMsg.innerHTML = d.message;
            
            if (d.code) {
                oVerifyUserNameMsg.style.color = \'red\';
            } else {
                oVerifyUserNameMsg.style.color = \'green\';
            }
        });
    }
    
    /*
    用户注册
    get/post
        guestbook/index.php
            m : index
            a : reg
            username : 要注册的用户名
            password : 注册的密码
        返回
            {
                code : 返回的信息代码 0 = 没有错误,1 = 有错误
                message : 返回的信息 具体返回信息
            }
    */
    var oPassword1 = document.getElementById(\'password1\');
    var oRegBtn = document.getElementById(\'btnReg\');
    oRegBtn.onclick = function() {
        
        ajax(\'post\', \'guestbook/index.php\', \'m=index&a=reg&username=\'+encodeURI(oUsername1.value)+\'&password=\' + oPassword1.value, function(data) {
            var d = JSON.parse(data);
            alert(d.message);
            
        });
        
    }
    
    /*
    用户登陆
    get/post
        guestbook/index.php
            m : index
            a : login
            username : 要登陆的用户名
            password : 登陆的密码
        返回
            {
                code : 返回的信息代码 0 = 没有错误,1 = 有错误
                message : 返回的信息 具体返回信息
            }
    */
    var oUsername2 = document.getElementById(\'username2\');
    var oPassword2 = document.getElementById(\'password2\');
    var oLoginBtn = document.getElementById(\'btnLogin\');
    oLoginBtn.onclick = function() {
        
        ajax(\'post\', \'guestbook/index.php\', \'m=index&a=login&username=\'+encodeURI(oUsername2.value)+\'&password=\' + oPassword2.value, function(data) {
            var d = JSON.parse(data);
            alert(d.message);
            
            if (!d.code) {
                updateUserStatus();
            }
            
        });
        
    }
    
    /*
    用户退出
    get/post
        guestbook/index.php
            m : index
            a : logout
        返回
            {
                code : 返回的信息代码 0 = 没有错误,1 = 有错误
                message : 返回的信息 具体返回信息
            }
    */
    var oLogout = document.getElementById(\'logout\');
    oLogout.onclick = function() {
        
        ajax(\'get\', \'guestbook/index.php\', \'m=index&a=logout\', function(data) {
            
            var d = JSON.parse(data);
            alert(d.message);
            
            if (!d.code) {
                //退出成功
                updateUserStatus();
            }
            
        });
        
        return false;
        
    }
    
    /*
    留言
    post
        guestbook/index.php
            m : index
            a : send
            content : 留言内容
        返回
            {
                code : 返回的信息代码 0 = 没有错误,1 = 有错误
                data : 返回成功的留言的详细信息
                    {
                        cid : 留言id    
                        content : 留言内容 
                        uid : 留言人的id
                        username : 留言人的名称
                        dateline : 留言的时间戳(秒)
                        support : 当前这条留言的顶的数量
                        oppose : 当前这条留言的踩的数量
                    }
                message : 返回的信息 具体返回信息
            }
    */
    var oContent = document.getElementById(\'content\');
    var oPostBtn = document.getElementById(\'btnPost\');
    oPostBtn.onclick = function() {
        
        ajax(\'post\', \'guestbook/index.php\', \'m=index&a=send&content=\'+encodeURI(oContent.value), function(data) {
            
            var d = JSON.parse(data);
            //alert(d.message);
            
            if (!d.code) {
                //添加当前留言到列表中
                createList(d.data, true);
            }
            
        });
        
    }
    
    //从后台返回的json的data
    function createList(data, insert) {
        var oDl = document.createElement(\'dl\');
                
        var oDt = document.createElement(\'dt\');
        var oStrong = document.createElement(\'strong\');
        oStrong.innerHTML = data.username;
        oDt.appendChild(oStrong);
        
        var oDd1 = document.createElement(\'dd\');
        oDd1.innerHTML = data.content;
        
        var oDd2 = document.createElement(\'dd\');
        oDd2.className = \'t\';
        var oA1 = document.createElement(\'a\');
        oA1.href = \'\';
        oA1.innerHTML = \'顶(<span>\'+data.support+\'</span>)\';
        var oA2 = document.createElement(\'a\');
        oA2.href = \'\';
        oA2.innerHTML = \'踩(<span>\'+data.oppose+\'</span>)\';
        oDd2.appendChild(oA1);
        oDd2.appendChild(oA2);
        
        oDl.appendChild(oDt);
        oDl.appendChild(oDd1);
        oDl.appendChild(oDd2);
        
        
        //oList存在留言就在oList前面插入留言insertBefore,否则直接插入留言appendChild
        if (insert && oList.children[0]) {
            oList.insertBefore(oDl, oList.children[0]);
        } else {
            oList.appendChild(oDl);
        }
    }
    
    //点击显示更多的内容
    oShowMore.onclick = function() {
        iPage++;
        showList();
    }
    
    function showList() {
        /*
        初始化留言列表
        get
            guestbook/index.php
                m : index
                a : getList
                page : 获取的留言的页码,默认为1
                n : 每页显示的条数,默认为10
            返回
                {
                    code : 返回的信息代码 0 = 没有错误,1 = 有错误
                    

以上是关于js封装简单实例源码记录的主要内容,如果未能解决你的问题,请参考以下文章

回归 | js实用代码片段的封装与总结(持续更新中...)

pjax简单实例

记录--九个超级好用的 Javascript 技巧

vue源码分析之目录架构

VsCode 代码片段-提升研发效率

如何使用 Jest 模拟封装在服务类中的 winston 记录器实例