当前位置: 主页 > 网页基础 > html >

前端常用函数和CSS常用技巧

时间: 2016-12-06 10:39 来源: 未知 作者: admin 点击:
前端常用函数和CSS常用技巧
 

对localStorage的封装,使用更简单

//在get时,如果是JSON格式,那么将其转换为JSON,而不是字符串。以下是基础代码:
var Store = {
    get: function(key) {
        var value = localStorage.getItem(key);
        if (value) {
            try {
                var value_json = JSON.parse(value);
                if (typeof value_json === 'object') {
                    return value_json;
                } else if (typeof value_json === 'number') {
                    return value_json;
                }
            } catch(e) {
                return value;
            }
        } else {
            return false;
        }
    },
    set: function(key, value) {
        localStorage.setItem(key, value);
    },
    remove: function(key) {
        localStorage.removeItem(key);
    },
    clear: function() {
        localStorage.clear();
    }
};
在此基础之上,可以扩展很多方法,比如批量保存或删除一些数据:
// 批量保存,data是一个字典
Store.setList = function(data) {
    for (var i in data) {
        localStorage.setItem(i, data[i]);
    }
};

// 批量删除,list是一个数组
Store.removeList = function(list) {
    for (var i = 0, len = list.length; i < len; i++) {
        localStorage.removeItem(list[i]);
    }
};

js判断滚动条是否到底部:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<script src=""></script>
		<style type="text/css">
			* {
				padding: 0px;
				margin: 0px;
			}
			#main {
				width: 100%;
				height: 2000px;
				background: pink;
			}
		</style>
		<script type="text/javascript">
			$(window).scroll(function() {  
				var scrollTop = $(this).scrollTop();  
				var docHeight = $(document).height();  
				var windowHeight = $(this).height();
				var scrollHeight=document.body.scrollHeight;
				console.log("scrollTop:"+scrollTop);
				console.log("scrollbottom:"+(docHeight-scrollTop-windowHeight));
				if(scrollTop + windowHeight == docHeight) {    
					alert("已经到最底部了!");  
				}
			});
		</script>
	</head>

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

</html>

js操作cookie

JS设置cookie:
 
假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为: 

document.cookie="name="+username;  

JS读取cookie:
 
假设cookie中存储的内容为:name=jack;password=123
 
则在B页面中获取变量username的值的JS代码如下:

var username=document.cookie.split(";")[0].split("=")[1];  

//JS操作cookies方法! 

//写cookies 

function setCookie(name,value{ 
    var Days = 30; 
    var exp = new Date(); 
    exp.setTime(exp.getTime() + Days*24*60*60*1000); 
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 

//读取cookies 
function getCookie(name{ 
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
 
    if(arr=document.cookie.match(reg))
 
        return unescape(arr[2]); 
    else 
        return null; 
} 

//删除cookies 
function delCookie(name{ 
    var exp = new Date(); 
    exp.setTime(exp.getTime() - 1); 
    var cval=getCookie(name); 
    if(cval!=null) 
        document.cookie= name + "="+cval+";expires="+exp.toGMTString(); 
} 
//使用示例 
setCookie("name","hayden"); 
alert(getCookie("name")); 

//如果需要设定自定义过期时间 
//那么把上面的setCookie 函数换成下面两个函数就ok; 


//程序代码 
function setCookie(name,value,time)
{ 
    var strsec = getsec(time); 
    var exp = new Date(); 
    exp.setTime(exp.getTime() + strsec*1); 
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); 
} 
function getsec(str)
{ 
   alert(str); 
   var str1=str.substring(1,str.length)*1; 
   var str2=str.substring(0,1); 
   if (str2=="s")
   { 
        return str1*1000; 
   }
   else if (str2=="h")
   { 
       return str1*60*60*1000; 
   }
   else if (str2=="d")
   { 
       return str1*24*60*60*1000; 
   } 
} 
//这是有设定过期时间的使用示例: 
//s20是代表20秒 
//h是指小时,如12小时则是:h12 
//d是天数,30天则:d30 

setCookie("name","hayden","s20");

获取URL参数:

 function GetURLlist(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if(r != null) return unescape(r[2]);
                return null;
            };

IOS和安卓判断:

var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if(isAndroid){
        $(".down0").css('display','none')
    }else if(isiOS){
        $(".down").css('display','none')
    }
    else{
        return false;
    }

判断微信:

function isWeiXin(){
                var ua = window.navigator.userAgent.toLowerCase();
                if(ua.match(/MicroMessenger/i) == 'micromessenger'){
                    return true;
                }else{
                    return false;
                }
            }
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1|| u.indexOf('MI') > -1|| <br>u.indexOf('XiaoMi') > -1; //android终端或者uc,小米等奇葩浏览器
    if(!isAndroid) {} 
    if(isAndroid)  {}

 

判断页面滚动方向:

<script type="text/javascript">
            $(function() {
                function scroll(fn) {
                    var beforeScrollTop = document.body.scrollTop,
                        fn = fn || function() {};
                    window.addEventListener("scroll", function() {
                        var afterScrollTop = document.body.scrollTop,
                            delta = afterScrollTop - beforeScrollTop;
                        if(delta === 0) return false;
                        fn(delta > 0 ? "down" : "up");
                        beforeScrollTop = afterScrollTop;
                    }, false);
                }
                scroll(function(direction) {
                    if(direction == "down") {
                        console.log("向下滚");
                    } else {
                        console.log("向上滚");
                    }
                });
            });
        </script>
 <script type="text/javascript">
        var windowHeight = $(window).height();
        $("body").css("height", windowHeight);
        var startX, startY, moveEndX, moveEndY, X, Y;
        $("body").on("touchstart", function(e) {
            e.preventDefault();
            startX = e.originalEvent.changedTouches[0].pageX, startY = e.originalEvent.changedTouches[0].pageY;
        });
        $("body").on("touchmove", function(e) {
            e.preventDefault();
            moveEndX = e.originalEvent.changedTouches[0].pageX, moveEndY = e.originalEvent.changedTouches[0].pageY, X = moveEndX - startX, Y = moveEndY - startY;
            if (Math.abs(X) > Math.abs(Y) && X > 0) {
                alert("left to right");
            } else if (Math.abs(X) > Math.abs(Y) && X < 0) {
                alert("right to left");
            } else if (Math.abs(Y) > Math.abs(X) && Y > 0) {
                alert("top to bottom");
            } else if (Math.abs(Y) > Math.abs(X) && Y < 0) {
                alert("bottom to top");
            } else {
                alert("just touch");
            }
        });
    </script>

排序

<script type="text/javascript">
            var a = [1, 18, 23, 9, 16, 10, 29, 17];
            var t = 0;
            for(var i = 0; i < a.length; i++) {
                for(var j = i + 1; j < a.length; j++) {
                    if(a[i] > a[j]) {
                        t = a[i];
                        a[i] = a[j];
                        a[j] = t;
                    }
                }
            }
            console.log(a);  //[1, 9, 10, 16, 17, 18, 23, 29]
        </script>

倒计时:

 <!Doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>下班倒计时</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }

            body {
                font-size: 16px;
                text-align: center;
                font-family: arial;
            }

            .time {
                margin-top: 10px;
                border: 1px solid red;
                height: 30px;
                padding: 2px;
                line-height: 30px;
            }
        </style>
    </head>

    <body>
        <div class="time">
            <span id="t_d">00天</span>
            <span id="t_h">00时</span>
            <span id="t_m">00分</span>
            <span id="t_s">00秒</span>
        </div>
        <script>
            setInterval(function() {
                var EndTime = new Date('2016/06/13 00:00:00');
                var NowTime = new Date();
                var t = EndTime.getTime() - NowTime.getTime();
                var d = 0;
                var h = 0;
                var m = 0;
                var s = 0;
                if (t >= 0) {
                    d = Math.floor(t / 1000 / 60 / 60 / 24);
                    h = Math.floor(t / 1000 / 60 / 60 % 24);
                    m = Math.floor(t / 1000 / 60 % 60);
                    s = Math.floor(t / 1000 % 60);
                }
                document.getElementById("t_d").innerHTML = d + "天";
                document.getElementById("t_h").innerHTML = h + "时";
                document.getElementById("t_m").innerHTML = m + "分";
                document.getElementById("t_s").innerHTML = s + "秒";
            }, 10);
        </script>

    </body>

</html>

类型判断:

function _typeOf(obj) {
		return Object.prototype.toString.call(obj).toLowerCase().slice(8, -1);  //
	}

判断undefined: 
<span style="font-size: small;">
var tmp = undefined; 
if (typeof(tmp) == "undefined"){ 
alert("undefined"); 
}
</span> 


判断null: 
<span style="font-size: small;">
var tmp = nullif (!tmp && typeof(tmp)!="undefined" && tmp!=0){ 
alert("null"); 
} 
</span> 

判断NaN: 
var tmp = 0/0if(isNaN(tmp)){ 
alert("NaN"); 
}


判断undefined和null: 
<span style="font-size: small;">
var tmp = undefined; 
if (tmp== undefined) 
{ 
alert("null or undefined"); 
}
 </span> 


<span style="font-size: small;">
var tmp = undefined; 
if (tmp== null) 
{ 
alert("null or undefined"); 
}
</span> 


判断undefined、null与NaN: 
<span style="font-size: small;">
var tmp = nullif (!tmp) 
{ 
alert("null or undefined or NaN"); 
}
</span> 

 

Ajax

jquery ajax函数

我自己封装了一个ajax的函数,代码如下:

var Ajax = function(url, type success, error) {
    $.ajax({
        url: url,
        type: type,
        dataType: 'json',
        timeout: 10000,
        success: function(d) {
            var data = d.data;
            success && success(data);
        },
        error: function(e) {
            error && error(e);
        }
    });
};
// 使用方法:
Ajax('/data.json', 'get', function(data) {
    console.log(data);
});

jsonp方式

有时候我们为了跨域,要使用jsonp的方法,我也封装了一个函数:

function jsonp(config) {
    var options = config || {};   // 需要配置url, success, time, fail四个属性
    var callbackName = ('jsonp_' + Math.random()).replace(".", "");
    var oHead = document.getElementsByTagName('head')[0];
    var oScript = document.createElement('script');
    oHead.appendChild(oScript);
    window[callbackName] = function(json) {  //创建jsonp回调函数
        oHead.removeChild(oScript);
        clearTimeout(oScript.timer);
        window[callbackName] = null;
        options.success && options.success(json);   //先删除script标签,实际上执行的是success函数
    };
    oScript.src = options.url + '?' + callbackName;    //发送请求
    if (options.time) {  //设置超时处理
        oScript.timer = setTimeout(function () {
            window[callbackName] = null;
            oHead.removeChild(oScript);
            options.fail && options.fail({ message: "超时" });
        }, options.time);
    }
};
// 使用方法:
jsonp({
    url: '/b.com/b.json',
    success: function(d){
        //数据处理
    },
    time: 5000,
    fail: function(){
        //错误处理
    }       
});

JS生成随机字符串的最佳实践

var random_str = function() {
    var len = 32;
    var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    var max = chars.length;
    var str = '';
    for (var i = 0; i < len; i++) {
    str += chars.charAt(Math.floor(Math.random() * max));
    }

    return str;
};
//这样生成一个32位的随机字符串,相同的概率低到不可能。

常用正则表达式

JavaScript过滤Emoji的最佳实践

name = name.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");

手机号验证:

var validate = function(num) {
    var reg = /^1[3-9]\d{9}$/;
    return reg.test(num);
};

身份证号验证:

var reg = /^[1-9]{1}[0-9]{14}$|^[1-9]{1}[0-9]{16}([0-9]|[xX])$/;

ip验证:

var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}$/

常用js函数

返回顶部:

$(window).scroll(function() {
    var a = $(window).scrollTop();
    if(a > 100) {
        $('.go-top').fadeIn();
    }else {
        $('.go-top').fadeOut();
    }
});
$(".go-top").click(function(){
    $("html,body").animate({scrollTop:"0px"},'600');
});

阻止冒泡:

function stopBubble(e){
    e = e || window.event;  
    if(e.stopPropagation){
        e.stopPropagation();  //W3C阻止冒泡方法  
    }else {  
        e.cancelBubble = true; //IE阻止冒泡方法  
    }  
}

全部替换replaceAll:

var replaceAll = function(bigStr, str1, str2) {  //把bigStr中的所有str1替换为str2
    var reg = new RegExp(str1, 'gm');
    return bigStr.replace(reg, str2);
}

获取浏览器url中的参数值:

var getURLParam = function(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)', "ig").exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null;
};

深度拷贝对象:

function cloneObj(obj) {
    var o = obj.constructor == Object ? new obj.constructor() : new obj.constructor(obj.valueOf());
    for(var key in obj){
        if(o[key] != obj[key] ){
            if(typeof(obj[key]) == 'object' ){
                o[key] = mods.cloneObj(obj[key]);
            }else{
                o[key] = obj[key];
            }
        }
    }
    return o;
}

数组去重:

var unique = function(arr) {
    var result = [], json = {};
    for (var i = 0, len = arr.length; i < len; i++){
        if (!json[arr[i]]) {
            json[arr[i]] = 1;
            result.push(arr[i]);  //返回没被删除的元素
        }
    }
    return result;
};

判断数组元素是否重复:

var isRepeat = function(arr) {  //arr是否有重复元素
    var hash = {};
    for (var i in arr) {
        if (hash[arr[i]]) return true;
        hash[arr[i]] = true;
    }
    return false;
};

生成随机数:

function randombetween(min, max){
    return min + (Math.random() * (max-min +1));
}

操作cookie:

own.setCookie = function(cname, cvalue, exdays){
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = 'expires='+d.toUTCString();
    document.cookie = cname + '=' + cvalue + '; ' + expires;
};
own.getCookie = function(cname) {
    var name = cname + '=';
    var ca = document.cookie.split(';');
    for(var i=0; i< ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return '';
};

数据类型: underfined、null、0、false、NaN、空字符串。他们的逻辑非结果均为true。

闭包格式: 好处:避免命名冲突(全局变量污染)。

(function(a, b) {
    console.log(a+b);  //30
})(10, 20);

截取和清空数组:

var arr = [12, 222, 44, 88];
arr.length = 2;   //截取,arr = [12, 222];  
arr.length = 0;   //清空,arr will be equal to [].

获取数组的最大最小值:

var numbers = [5, 45822, 120, -215];
var maxInNumbers = Math.max.apply(Math, numbers);   //45822
var minInNumbers = Math.min.apply(Math, numbers);   //-215

浮点数计算问题:

0.1 + 0.2 == 0.3   //false

为什么呢?因为0.1+0.2等于0.30000000000000004。JavaScript的数字都遵循IEEE 754标准构建,在内部都是64位浮点小数表示。可以通过使用toFixed()来解决这个问题。

数组排序sort函数:

var arr = [1, 5, 6, 3];    //数字数组
arr.sort(function(a, b) {
    return a - b;   //从小到大排
    return b - a;   //从大到小排
    return Math.random() - 0.5;   //数组洗牌
});
var arr = [{   //对象数组
    num: 1,
    text: 'num1'
}, {
    num: 5,
    text: 'num2'
}, {
    num: 6,
    text: 'num3'
}, {
    num: 3,
    text: 'num4'
}];   
arr.sort(function(a, b) {
    return a.num - b.num;   //从小到大排
    return b.num - a.num;   //从大到小排
});

对象和字符串的转换:

var obj = {a: 'aaa', b: 'bbb'};
var objStr = JSON.stringify(obj);    // "{"a":"aaa","b":"bbb"}"
var newObj = JSON.parse(objStr);     // {a: "aaa", b: "bbb"}

git笔记

git使用之前的配置:

1.git config --global user.email xxx@163.com
2.git config --global user.name xxx
3.ssh-keygen -t rsa -C xxx@163.com(邮箱地址)      // 生成ssh
4.找到.ssh文件夹打开,使用cat id_rsa.pub    //打开公钥ssh串
5.登陆github,settings - SSH keys  - add ssh keys (把上面的内容全部添加进去即可)

说明:然后这个邮箱(xxxxx@gmail.com)对应的账号在github上就有权限对仓库进行操作了。可以尽情的进行下面的git命令了。

git常用命令:

1、git config user.name  /  user.email     //查看当前git的用户名称、邮箱
2、git clone https://github.com/jarson7426/javascript.git  project  //clone仓库到本地。
3、修改本地代码,提交到分支:  git add file   /   git commit -m “新增文件”
4、把本地库推送到远程库:  git push origin master
5、查看提交日志:git log -5
6、返回某一个版本:git reset --hard 123
7、分支:git branch / git checkout name  / git checkout -b dev
8、合并name分支到当前分支:git merge name   /   git pull origin
9、删除本地分支:git branch -D name
10、删除远程分支: git push origin  :daily/x.x.x
11、git checkout -b mydev origin/daily/1.0.0    //把远程daily分支映射到本地mydev分支进行开发
12、合并远程分支到当前分支 git pull origin daily/1.1.1
13、发布到线上:
    git tag publish/0.1.5
    git push origin publish/0.1.5:publish/0.1.5
14、线上代码覆盖到本地:
    git checkout --theirs build/scripts/ddos
    git checkout --theirs src/app/ddos

 

判断是否有中文:

var reg = /.*[\u4e00-\u9fa5]+.*$/;
reg.test('123792739测试')  //true

判断是对象还是数组:

function isArray = function(o) {
    return toString.apply(o) === '[object Array]';
}
function isObject = function(o) {
    return toString.apply(o) === '[object Object]';
}

CSS修改滚动条样式:

::-webkit-scrollbar {
	width: 10px;
	background-color: #ccc;
}
::-webkit-scrollbar-track {
	background-color: #ccc;
	border-radius: 10px;
}
::-webkit-scrollbar-thumb {
	background-color: rgb(255, 255, 255);
	background-image: -webkit-gradient(linear, 40% 0%, 75% 84%, from(rgb(77, 156, 65)), color-stop(0.6, rgb(84, 222, 93)), to(rgb(25, 145, 29)));
	border-radius: 10px;
}

单行多行省略号:

       <style type="text/css">  
            .inaline {  
                overflow: hidden;  
                white-space: nowrap;  
                text-overflow: ellipsis;  
                /*clip  修剪文本。*/  
            }  
              
            .intwoline {  
                display: -webkit-box !important;  
                overflow: hidden;  
                text-overflow: ellipsis;  
                word-break: break-all;  
                -webkit-box-orient: vertical;  
                -webkit-line-clamp3;  
            }  
        </style>  

遮罩:

<!doctype html>
<html lang="en">

	<head>
		<meta charset="UTF-8" />
		<title>RGBA 遮罩</title>
		<style type="text/css">
			* {
				padding: 0px;
				margin: 0px;
			}
			
			html,
			body {
				width: 100%;
				min-height: 100%;
				background: white;
			}
			
			div.mask {
				display: none;
				position: fixed;
				top: 0px;
				left: 0px;
				width: 100%;
				height: 100%;
				background: rgba(0, 0, 0, 0.7);
			}
			
			div.masks-body {
				width: 300px;
				height: 300px;
				position: absolute;
				top: 0px;
				left: 0px;
				bottom: 0px;
				right: 0px;
				background: green;
				margin: auto;
			}
			
			p {
				position: absolute;
				width: 30px;
				height: 30px;
				background: red;
				right: 0px;
				top: -30px;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				document.querySelector("#main").onclick = function() {
					document.querySelector(".mask").style.display = "block";
				}
				document.querySelector("p#close").onclick=function(){
					document.querySelector(".mask").style.display = "none";
				}
			}
		</script>
	</head>

	<body>
		<button id="main">点我</button>
		<div class="mask">
			<div class="masks-body">
				<p id="close"></p>
			</div>
		</div>
	</body>

</html>

常见页面flex布局:

<!doctype html>
<html lang="en">

	<head>
		<meta charset="UTF-8" />
		<title></title>
		<style type="text/css">
			* {
				padding: 0px;
				margin: 0px;
			}
			
			html,
			body {
				width: 100%;
				min-height: 100%;
				min-width: 1200px;
				overflow-x: hidden;
			}
			
			h1 {
				color: red;
				text-align: center;
			}
			
			#main0 {
				height: 400px;
				background: black;
				display: flex;
				flex-flow: row wrap;
				justify-content: flex-start;
				align-items: flex-start;
			}
			
			#main0 div:nth-child(2n) {
				flex: 1;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: red;
			}
			
			#main0 div:nth-child(2n+1) {
				flex: 1;
				height: 200px;
				line-height: 200px;
				font-size: 100px;
				text-align: center;
				background: blue;
			}
			
			#main1 {
				height: 400px;
				background: pink;
				display: flex;
				flex-flow: row nowrap;
				justify-content: flex-start;
				align-items: flex-start;
			}
			
			#main1 div:nth-child(2n) {
				flex: 1;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: red;
			}
			
			#main1 div:nth-child(2n+1) {
				width: 300px;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: blue;
			}
			
			#main2 {
				height: 400px;
				background: yellow;
				display: flex;
				flex-flow: row nowrap;
				justify-content: flex-start;
				align-items: flex-start;
			}
			
			#main2 div:nth-child(2n) {
				flex: 1;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: red;
			}
			
			#main2 div:nth-child(2n+1) {
				width: 300px;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: blue;
			}
			
			#main3 {
				height: 400px;
				background: fuchsia;
				display: flex;
				flex-flow: row nowrap;
				justify-content: flex-start;
				align-items: flex-start;
			}
			
			#main3 div.div1 {
				flex: 1;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: blue;
			}
			
			#main3 div.div2 {
				flex: 2;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: red;
			}
			
			#main3 div.div3 {
				flex: 3;
				height: 200px;
				font-size: 100px;
				line-height: 200px;
				text-align: center;
				background: orange;
			}
		</style>
	</head>

	<body>
		<h1>等分布局</h1>
		<div id="main0">
			<div>1</div>
			<div>2</div>
			<div>3</div>
			<div>4</div>
			<div>5</div>
		</div>
		<h1>左边固定右边自适应布局</h1>
		<div id="main1">
			<div>1</div>
			<div>2</div>
		</div>
		<h1>左右固定中间自适应布局</h1>
		<div id="main2">
			<div>1</div>
			<div>2</div>
			<div>3</div>
		</div>
		<h1>宽度等差布局</h1>
		<div id="main3">
			<div class="div1">1</div>
			<div class="div2">2</div>
			<div class="div3">3</div>
		</div>
	</body>

</html>

flex: 1的使用:

 

 

<!doctype html>
<html lang="en">

	<head>
		<meta charset="UTF-8" />
		<title>Document</title>
		<style type="text/css">
			* {
				padding: 0px;
				margin: 0px;
			}
			
			#main {
				display: flex;
				align-items: center;
			}
			
			h1 {
				background: red;
				flex: 1;
				text-align: center;
			}
		</style>
	</head>

	<body>
		<div id="main">
			<p>哈哈哈</p>
			<h1>啊啊啊</h1>
			<div>呜呜呜</div>
		</div>
	</body>

</html>

单行超出省略字

 .div{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap; 
}

placeholder颜色

input::-webkit-input-placeholder{
  color: #666;
}

禁止文本选择

.div{
  -moz-user-select:none;
  -webkit-user-select:none;
  -ms-user-select:none;
  -khtml-user-select:none;
  user-select:none;
}

iOS惯性滚动

.div{
  -webkit-overflow-scrolling:touch !important;
}

表单100%宽,但是有padding

input{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

字体细长

.div{
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

横向滚动

.div{
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
}

(责任编辑:admin)
------分隔线----------------------------