a个人经验总结2

金额

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="../19form/common.css"/>
    <style>
        .money_unit,.money-edit{background: url("money_rp.png") repeat-y;}
        .money_unit{height: 22px; line-height: 22px;}
        .money_unit span{width:19px;display:inline; text-align: center;float: left;font-size: 12px;margin-right:1px;}
        .money_unit span.last{width:18px;margin-right:0;}
        .money-edit{letter-spacing: 13px;text-align: right;overflow: hidden; font-size: 14px;}
    </style>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td width="100">111111111</td>
        <td width="219">
            <div class="money_unit">
                <span>亿</span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span class="last"></span>
            </div>
        </td>
    </tr>
    <tr>
        <td>111111111</td>
        <td>
            <div class="money-edit">
                <input type="text" name="" class="money" />
            </div>
        </td>
    </tr>
    <tr>
        <td>111111111</td>
        <td>
            <div class="money-edit">
                <input type="text" name="" class="money" />
            </div>
        </td>
    </tr>
</table>
<p></p>
    <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(function () {
        $(".money-edit").click(function () {
            $(this).find("span").remove();
            $(this).find(".money").show().focus().select();
        });
        $(".money").keyup(function () {
            //只能输入数字和点
            this.value=this.value.replace(/[^\d.]/g,"");    //保证第一个为数字而不是.
            this.value=this.value.replace(/\.{2,}/g,".");  //保证不能连续输入两个.
            this.value = this.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");  //    输入过程解决  3.234.235.43  =》 3.234
        });
            var arr=[];
            var money=0;
        $(".money").blur(function () {
            var total = 0;
            var index=$(this).parent().parent().parent().index()-1;  //  让index最终等于0 
            console.log("xx: index"+index);  
            console.log("xx:1 "+$(this).val());
            if($(this).val()==""){   //如果值为空,直接隐藏
                $(this).hide();
            }else{
             money=format($(this).val());
            if(money.length>11){
                alert("数字超出最大范围");
                return $(this).select();
            }
            $(this).parent().append("<span style='margin-right: -8px;width:221px; overflow: hidden;'>"+money+"</span>");
                    arr[index]=parseInt(money);
                if(arr.length>0){
                    for(var i=0;i<arr.length;i++){
                        total+=arr[i];
                    }
                    $("p").text(total.toString());
                }
            $(this).val((parseFloat(money)/100).toFixed(2));
            $(this).hide();
            }

        });



        //四舍五入   var a=123;  a.toFixed(2)  四舍五入,保留2位小数
        function format(num){
           // num=parseFloat(num).toString();    //    解决  3.234.235.43  =》 3.234
            if(num.indexOf(".")==-1){  // 整数
                return num+"00";
            }else{
                //return ((parseFloat(num).toFixed(2))*100).toString();
                return (Math.round(parseFloat(num)*100)).toString();    // 解决 546.546问题
                /*return (parseFloat(parseFloat(num).toFixed(2)).mul(100)).toString();*/
            };
        }
        //  浮点数乘法
        //   一般情况下 546.55*100=  54654.99999999999
        function accMul(arg1,arg2)
        {
            var m=0,s1=arg1.toString(),s2=arg2.toString();
            try{m+=s1.split(".")[1].length}catch(e){}
            try{m+=s2.split(".")[1].length}catch(e){}
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
        }
        Number.prototype.mul = function (arg){
            return accMul(arg, this);
        }
    });
</script>
</body>
</html>
money_rp.png

jquery 购物车总价

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery实现购物车多物品数量的加减+总价计算</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
    <script>
        $(function(){
            $(".add").click(function(){
                var t=$(this).parent().find('input[class*=text_box]');
                t.val(parseInt(t.val())+1)
                setTotal();
            })
            $(".min").click(function(){
                var t=$(this).parent().find('input[class*=text_box]');
                t.val(parseInt(t.val())-1)
                if(parseInt(t.val())<0){
                    t.val(0);
                }
                setTotal();
            })
            function setTotal(){
                var s=0;
                $("#tab td").each(function(){
                    s+=parseInt($(this).find('input[class*=text_box]').val())*parseFloat($(this).find('span[class*=price]').text());
                });
                $("#total").html(s.toFixed(2));
            }
            setTotal();

        })
    </script>
</head>
<body>
<table id="tab">
    <tr>
        <td>
            <span>单价:</span><span class="price">1.50</span>
            <input class="min" name="" type="button" value="-" />
            <input class="text_box" name="" type="text" value="1" />
            <input class="add" name="" type="button" value="+" />
        </td>
    </tr>
    <tr>
        <td>
            <span>单价:</span><span class="price">3.95</span>
            <input class="min" name="" type="button" value="-" />
            <input class="text_box" name="" type="text" value="1" />
            <input class="add" name="" type="button" value="+" />
        </td>
    </tr>
</table>

<p>总价:<label id="total"></label></p>
</body>
</html> 

 checkbox 大小,对齐方式

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        p{line-height: 30px;border: 1px solid red;}
        input[type="checkbox"]{
            vertical-align: middle;  /* 边框与文字对齐*/
            width:20px;height: 20px;  /*边框大小 */
        }
    </style>
</head>
<body>
<p>
<input type="checkbox"/>普通 <input type="checkbox"/>加急
</p>
</body>
</html>

 prototype 原型继承

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(function () {
            $("button").click(function () {
            var val=$("#name").val().trimAll();
                alert(val);
            });
            // 原型继承  去掉所有空格
            String.prototype.trimAll= function () {
                return this.replace(/\s/g,"");
            }
        });
    </script>
</head>
<body>
<input type="text" id="name"/>
<button>btn</button>
</body>
</html>
View Code

 js优化技巧

1.使用 === 代替 == 如果两边的操作数具有相同的类型和值,=== 返回true, !== 返回 false;
2. JSLint 检查代码问题和错误。
3. 把js放在body结束之前, 目标是让页面尽可能快的呈献给用户。
4. for(var i=0,len=xx.length;i<len;i++){
// 不需要每次循环都计算机数组的长度。
}

5.构建字符串的最优方法

 //少用for语句,原生代码(join())通常比非原生快很多。
    $(function () {
        var arr= ['file','edit','view'];
        var list='<ul><li>'+arr.join('</li><li>')+'</li></ul>';
        $("body").append(list);
    });

6.减少全局变量

<script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(function () {
        // 方式一
        var name='abc';
        var lastName='wp';
        function test(){}
        console.log(name);
        // 方式二
       /* var Person={
            name:'xiao',
            age:'12',
            skill: function () {
                return 'i am good at swimming';
            }
        }
       alert(Person.skill());*/
        // 方式三
        var Student=Student || {};
        Student.name='he';
        Student.age=12;
        Student.skill= function () {
            return this.name+' is shy';
        }
        alert(Student.skill());

    });
</script>
View Code

 7. 自调用匿名函数 

(function () {
alert(1);
})();

原生代码永远比库快 javascript比jquery快,js的for比Jquery的 each()快

8.函数传入对象参数

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script>
       var googleMap={
           show: function () {
               console.log("google... ");
           }
       }
       var baiduMap={
           show: function () {
               console.log("baidu... ");
           }
       }
        /*var renderMap= function (type) {
            if(type==='google'){
                googleMap.show();
            }else if(type==='baidu'){
                baiduMap.show();
            }
        }*/
       var renderMap= function (map) {
           /*if(map.show instanceof  Function){
               map.show();
           }*/
           map.show();
       }
    renderMap(googleMap);   // 传入一个对象参数!
</script>
</body>
</html>
View Code

 9.JS得到一个对象的3种方式

js要得到一个对象,不是通过实例化类,而是找到一个对象作为原型并克隆它

javascript的根对象是Object.prototype,这个是原型

Object.create();  底层实现

<script type="text/javascript">
    // 克隆一个飞机   Object.create();  2009年 ES5新增的,效率比 new 一个构造器慢
    
    var Plane = function(){
        this.blood = 100;
        this.attackLevel = 1;
        this.defenseLevel = 1;
    };

    var plane = new Plane();
    plane.blood = 500;
    plane.attackLevel = 10;
    plane.defenseLevel = 7;

    var clonePlane = Object.create( plane );
    console.log( clonePlane );  // 输出:Object {blood: 500, attackLevel: 10, defenseLevel: 7}

    //在不支持Object.create 方法的浏览器中,则可以使用以下代码:
    Object.create = Object.create || function( obj ){
        var F = function(){};
        F.prototype = obj;
        return new F();
    }

</script>
View Code

简单实现

var obj1= new Object() 或 var obj2 = {}; 

构造器实现(当使用new 来调用函数时,此时的函数就是一个构造器,实际上也是先克隆Object.prototype,再做其他)

<script>
  function Person(name){
     this.name=name; 
  }
    Person.prototype.getName= function () {
        return this.name;
    }
    var a = new Person('aaa');
    console.log("xx: "+ a.getName());
</script>
View Code

 10.this的指向

10.1  作为对象的方法调用

var obj={
    a:1,
      getA: function () {
          alert(this.a); // 输出: 1
      }
  };
    obj.getA();
View Code

10.2作为普通函数调用

 window.name='globalName';
    var getName= function () {
        return this.name;             //  全局 this 指向  window
    }
    alert(getName());  //  globalName;
View Code

10.3构造器调用

 var MyClass= function () {
        this.name='sven';
    }
    var obj=new MyClass();
    alert(obj.name);  // sven
View Code

10.4 Function.prototype.call 或  apply 动态改变传入函数的this 

 var obj={
       name:'sven',
       getName: function () {
           return this.name;
       }
   };
    var obj2={
        name:'aaa'
    };
    console.log("xx: "+obj1.getName());       // sven
    console.log("xx: "+obj.getName().call(obj2));    //aaa
View Code

 11. 对象方法调用、普通函数调用区别

var obj = {
        myName: 'sven',
        getName: function(){
            return this.myName;
        }
    };
    console.log( obj.getName() ); // 输出:'sven' 对象调用函数,指向 obj
    var getName2 = obj.getName;   // 用一个变量来引用,普通函数调用方式,指向windows
    console.log( getName2() ); // 输出:undefined
View Code

 12. call/apply 改变this 指向

document.getElementById('div1').onclick= function () {
        alert(this.id);       // div1
        var func= function () {
            alert(this.id);
        };
        func(); //  undefined  普通函数调用
        func.call(this);   // div1 把 this 指向 div1
    }
View Code

 13.

(function (){
"use strict"
alert(this); // undefined
})(); // ECMAScript 5 的 strict模式下,this被规定不指向全局对象

14. 手机测试地址栏Hash/锚点,返回按钮
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>测试地址栏Hash/锚点,返回按钮</title>
    <style>
        div {
            width: 200px;
            height: 100px;
            display: none;
            font-size: 5em;
        }
    </style>
</head>
<body>
<div id="div1" onclick="divClick('div2')" style="background-color: yellow;display: block;">Div1</div>
<div id="div2" onclick="divClick('div3')" style="background-color: red;">Div2</div>
<div id="div3" onclick="divClick('div4')" style="background-color: green;">Div3</div>
<div id="div4" onclick="divClick('div1')" style="background-color: blue;">Div4</div>

</body>
<script>
    //给页面绑定hashchange事件
    window.onhashchange = function(){
        var hashCode = location.hash;
        var _id = hashCode.substr(1);//去掉#,获取后面带的参数
        console.log("xx: "+_id);
        divchange(_id);
    };

    //div点击事件
    function divClick(_id){
        location.href = "#"+_id;
    }

    //div切换触发
    function divchange(_id){
        div1.style.display = 'none';
        div2.style.display = 'none';
        div3.style.display = 'none';
        div4.style.display = 'none';

        document.getElementById(_id).style.display = 'block';
    }

</script>
</html>
View Code

 15.图片自适应居中

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
    body{position:relative;}
        img{position:absolute;left:50%;margin-left:-100px;}
    </style>  
</head>
<body>
<img src="pic.png" width="200"/>
</body>
</html>
View Code

 16.带小图标的tab 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <style>
        body,div,i{margin:0;padding:0;}
        #foot_menu{
            /*    display: flex;
                flex-flow: row;
            */
            position:fixed;
            bottom:0;
            height:50px;
            padding:5px 0;
            box-shadow: 0px -5px 11px #c6c3c7;
            width:100%;
            background:#FFF;
        }
        #foot_menu div{
            /*    flex: 1;
            */
            float:left;
            width:25%;
            /*    margin:3px;*/
            text-align:center;
        }
        #foot_menu div i{
            width:20px;
            height:20px;
            background:url(icon_1.png) no-repeat;
            background-size:850%;    /* 这一行 不懂。。*/
            display:inline-block;
            color:#727171;
        }
        #foot_menu div .i1{
            background-position:0px -18px;
        }
        #foot_menu div .i11{
            background-position:0px 2px;
        }
        #foot_menu div .i2{
            background-position:-26px -18px;
        }
        #foot_menu div .i22{
            background-position:-26px 2px;
        }

        #foot_menu div .i3{
            background-position:-50px -18px;
        }

        #foot_menu div .i33{
            background-position:-50px 2px;
        }

        #foot_menu div .i4{
            background-position:-74px -18px;
        }
        #foot_menu div .i44{
            background-position:-74px 2px;
        }
        /*底部菜单*/

    </style>
    <script src="http://apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(function () {
            $("#foot_menu div").click(function () {
                var div_i = $('#foot_menu div i');
                var num = $(this).index()+1;
                re_class = 'i'+num+num;
                ad_class = 'i'+num;
                for(var a = 0; a<div_i.length ; a++){
                    $('#foot_menu div').eq(a).find('i').removeClass('i'+(a+1)).addClass('i'+(a+1)+(a+1));
                }
                $(this).find('i').removeClass(re_class).addClass(ad_class);

            });
        });
    </script>
</head>
<body>
<div class="height60"></div>
<div id="foot_menu">
    <div>
        <i class="i1"></i><br/>
        首页
    </div>
    <div>
        <i class="i22"></i><br/>
        采购大厅
    </div>
    <div>
        <i class="i33"></i><br/>
        生意圈
    </div>
    <div>
        <i class="i44"></i><br/>
        我的
    </div>
</div>
</body>
</html>
View Code

使用background-size:850%;是因为图片尺寸为40px 网页只有20px大小

17. js找不到则 return null 

 var arr=[4,651,56,2,5,8];
       function get(id){
         for(var i =0;i<arr.length;i++){
           if(arr[i]===parseInt(id)){
             return arr[i];
           }
         }
         //return "没有这个值";
         return null;  // 如果 找不到,就返回空
       }
      var res=get(989);
      //var res=get(56);  找到就返回
      alert(res);
View Code

 18.PC网页窗口变化时,重新加载页面,手机不受影响

if(!navigator.userAgent.toLocaleLowerCase().match(/(iphone|ipod|ipad|android)/)){
        
        $(window).resize(function(){
            location.reload();
        })
    }
View Code

 

posted @ 2016-07-22 15:40  gyz418  阅读(175)  评论(0)    收藏  举报