代码收集

css

全站变灰

html{
filter: grayscale(100%);
 -webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: url("data:image/svg+xml;utf8,<svg xmlns=\"http://www.w3.org/2000/svg\"><filter id=\"grayscale\"><feColorMatrix type=\"matrix\" values=\"0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\"/></filter></svg>#grayscale");
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
filter: gray;
-webkit-filter: grayscale(1);
}

loading 效果

订单提交中<dot>...</dot>
dot {
  display: inline-block;
  height: 1em; line-height: 1;
  text-align: left;
  vertical-align: -.25em;
  overflow: hidden;
}
dot::before {
  display: block;
  content: '...\A..\A.';
  white-space: pre-wrap;   /* 也可以是white-space: pre */
  animation: dot 3s infinite step-start both;
}
@keyframes dot {
  33% { transform: translateY(-2em); }
  66% { transform: translateY(-1em); }
}

https://jsfiddle.net/mxm145/2885v0ee/

loading 效果 2

<div class="container">
  <div class="ball ball1"></div>
  <div class="ball ball2"></div>
  <div class="ball ball3"></div>
</div>
.container {
  text-align: center;
}

.ball {
  display: inline-block;
  width: 1vw;
  height: 1vw;
  background-color: #333;
  margin: 1vh;
  border-radius: 50%;
}

.ball1 {
  animation: move 1s ease-in infinite alternate;
}

.ball2 {
  animation: move 1s linear infinite alternate;
}

.ball3 {
  animation: move 1s ease-out infinite alternate;
}

@keyframes move {
  100% {
    transform: translateY(5vw);
  }
}

箭头

<div class="comment"></div>
.comment {
  position: relative;
  width: 150px;
  height: 35px;
  background: #f8ac09;
  border-radius: 5px;
  margin: 30px auto 0;
}

.comment:after {
  content: '';
  position:absolute;
  top: 10px;
  right: -4px;
  width: 8px;
  height: 8px;
  transform: rotate(45deg);
  background-color: #f8ac09;
}

https://jsfiddle.net/mxm145/vLktgey2/

使用 :not() 在菜单上应用/取消应用边框

//两步
.nav li {
  border-right: 1px solid #666;
}
.nav li:last-child {
  border-right: none;
}
//一步
.nav li:not(:last-child) {
  border-right: 1px solid #666;
}

优化显示文本

html {
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

表格单元格等宽

.calendar {
  table-layout: fixed;
}

禁止复制、选中文本

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

html

跳转

<meta http-equiv="refresh" content="0;url=http://www.baidu.com/">

####禁止 favicon 请求

<link rel="icon" href="data:image/ico;base64,aWNv">

Loading

<div style="width: 100px;height: 100px; background: rgba(0,0,0,.8);">
    <svg version="1.1" id="L7" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
      <path fill="#fff" d="M31.6,3.5C5.9,13.6-6.6,42.7,3.5,68.4c10.1,25.7,39.2,38.3,64.9,28.1l-3.1-7.9c-21.3,8.4-45.4-2-53.8-23.3 c-8.4-21.3,2-45.4,23.3-53.8L31.6,3.5z" transform="rotate(294.276 50 50)">
        <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="2s" from="0 50 50" to="360 50 50" repeatCount="indefinite"></animateTransform>
      </path>
      <path fill="#fff" d="M42.3,39.6c5.7-4.3,13.9-3.1,18.1,2.7c4.3,5.7,3.1,13.9-2.7,18.1l4.1,5.5c8.8-6.5,10.6-19,4.1-27.7 c-6.5-8.8-19-10.6-27.7-4.1L42.3,39.6z" transform="rotate(-228.553 50 50)">
        <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s" from="0 50 50" to="-360 50 50" repeatCount="indefinite"></animateTransform>
      </path>
      <path fill="#fff" d="M82,35.7C74.1,18,53.4,10.1,35.7,18S10.1,46.6,18,64.3l7.6-3.4c-6-13.5,0-29.3,13.5-35.3s29.3,0,35.3,13.5 L82,35.7z" transform="rotate(294.276 50 50)">
        <animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="2s" from="0 50 50" to="360 50 50" repeatCount="indefinite"></animateTransform>
      </path>
    </svg>
</div>

javascript

图片 lazyload

document.addEventListener("DOMContentLoaded", function() {
  var lazyloadImages;
  if ("IntersectionObserver" in window) {
    lazyloadImages = document.querySelectorAll(".lazy");
    var imageObserver = new IntersectionObserver(function(entries, observer) {
      entries.forEach(function(entry) {
        if (entry.isIntersecting) {
          var image = entry.target;
          image.src = image.dataset.src;
          image.classList.remove("lazy");
          imageObserver.unobserve(image);
        }
      });
    });
    lazyloadImages.forEach(function(image) {
      imageObserver.observe(image);
    });
  } else {
    var lazyloadThrottleTimeout;
    lazyloadImages = document.querySelectorAll(".lazy");

    function lazyload () {
      if(lazyloadThrottleTimeout) {
        clearTimeout(lazyloadThrottleTimeout);
      }
      lazyloadThrottleTimeout = setTimeout(function() {
        var scrollTop = window.pageYOffset;
        lazyloadImages.forEach(function(img) {
            if(img.offsetTop < (window.innerHeight + scrollTop)) {
              img.src = img.dataset.src;
              img.classList.remove('lazy');
            }
        });
        if(lazyloadImages.length == 0) {
          document.removeEventListener("scroll", lazyload);
          window.removeEventListener("resize", lazyload);
          window.removeEventListener("orientationChange", lazyload);
        }
      }, 20);
    }
    document.addEventListener("scroll", lazyload);
    window.addEventListener("resize", lazyload);
    window.addEventListener("orientationChange", lazyload);
  }
})

cookie

添加 cookie

function addCookie(objName,objValue,objHours,objDomain,objPath){
	var str = objName + "=" + escape(objValue);
      if(objHours > 0){ //为时不设定过期时间,浏览器关闭时cookie自动消失
      var date = new Date();
      var ms = objHours*3600*1000;
      date.setTime(date.getTime() + ms);
      str += "; expires=" + date.toGMTString();
      if(objDomain){
          str += ";domain="+objDomain;
      }
      if(objPath){
          str += ";path="+objPath;
      }
  }
  document.cookie = str;
}

获取指定名称的 cookie 的值

function getCookie(objName){
	var arrStr = document.cookie.split("; ");
	for(var i = 0;i < arrStr.length;i ++){
	 var temp = arrStr[i].split("=");
	 if(temp[0] == objName) return unescape(temp[1]);
	}
}

删除指定名称的 cookie,可以将其过期时间设定为一个过去的时间

function delCookie(name){
  var date = new Date();
  date.setTime(date.getTime() - 10000);
  document.cookie = name + "=a; expires=" + date.toGMTString();
}

node class

是否存在某个 class

function hasClass(node,classname){
  return node.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

对节点增加 class

function addClass(node,classname){
  if(!this.hasClass(node,classname)){
    node.className = (node.className+" "+classname).replace(/^\s+|\s+$/g,'');
  }
}

对节点删除 class

function removeClass(node,classname){
  node.className = (node.className.replace(classname,"")).replace(/^\s+|\s+$/g,'');
}

数组

数组复制

var a = [1,2,3];
b = a.slice(0);

获取数组随机项

var items = [12, 548 , 'a' , 2 , 5478 , 'foo' , 8852, , 'Doe' , 2145 , 119];
var randomItem = items[Math.floor(Math.random() * items.length)];

类数组转换成数组

var args = [].slice.call(arguments);

是否在数组中

Array.prototype.inArray = function(value){
	for(var i = 0,l = this.length; i < 1; i ++){
		if(this[i] === value){
			return true;
		}
	}
	return false;
};

正则表达式


1. 数字:^[0-9]*$

2. n位的数字:^\d{n}$

3. 至少n位的数字:^\d{n,}$

4. m-n位的数字:^\d{m,n}$

5. 零和非零开头的数字:^(0|[1-9][0-9]*)$

6. 非零开头的最多带两位小数的数字:^([1-9][0-9]*)+(.[0-9]{1,2})?$

7. 带1-2位小数的正数或负数:^(\-)?\d+(\.\d{1,2})?$

8. 正数、负数、和小数:^(\-|\+)?\d+(\.\d+)?$

9. 有两位小数的正实数:^[0-9]+(.[0-9]{2})?$

10. 有1~3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$

11. 非零的正整数:^[1-9]\d*$ 或 ^([1-9][0-9]*){1,3}$ 或 ^\+?[1-9][0-9]*$

12. 非零的负整数:^\-[1-9][]0-9"*$ 或 ^-[1-9]\d*$

13. 非负整数:^\d+$ 或 ^[1-9]\d*|0$

14. 非正整数:^-[1-9]\d*|0$ 或 ^((-\d+)|(0+))$

15. 非负浮点数:^\d+(\.\d+)?$ 或 ^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$

16. 非正浮点数:^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 或 ^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$

17. 正浮点数:^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ 或 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$

18. 负浮点数:^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ 或 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$

19. 浮点数:^(-?\d+)(\.\d+)?$ 或 ^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$

1. 汉字:^[\u4e00-\u9fa5]{0,}$

2. 英文和数字:^[A-Za-z0-9]+$ 或 ^[A-Za-z0-9]{4,40}$

3. 长度为3-20的所有字符:^.{3,20}$

4. 由26个英文字母组成的字符串:^[A-Za-z]+$

5. 由26个大写英文字母组成的字符串:^[A-Z]+$

6. 由26个小写英文字母组成的字符串:^[a-z]+$

7. 由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$

8. 由数字、26个英文字母或者下划线组成的字符串:^\w+$ 或 ^\w{3,20}$

9. 中文、英文、数字包括下划线:^[\u4E00-\u9FA5A-Za-z0-9_]+$

10. 中文、英文、数字但不包括下划线等符号:^[\u4E00-\u9FA5A-Za-z0-9]+$ 或 ^[\u4E00-\u9FA5A-Za-z0-9]{2,20}$

11. 可以输入含有^%&',;=?$\"等字符:[^%&',;=?$\x22]+ 12 禁止输入含有~的字符:[^~\x22]+

12. 非打印的特殊字符匹配:[\u0000-\u001F]

1. Email地址:^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$

2. 域名:[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?

3. InternetURL:[a-zA-z]+://[^\s]* 或 ^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$

4. 手机号码:^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$

5. 电话号码("XXX-XXXXXXX"、"XXXX-XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX):^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$

6. 国内电话号码(0511-4405222、021-87888822):\d{3}-\d{8}|\d{4}-\d{7}

7. 身份证号(15位、18位数字):^\d{15}|\d{18}$

8. 短身份证号码(数字、字母x结尾):^([0-9]){7,18}(x|X)?$ 或 ^\d{8,18}|[0-9x]{8,18}|[0-9X]{8,18}?$

9. 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线):^[a-zA-Z][a-zA-Z0-9_]{4,15}$

10. 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线):^[a-zA-Z]\w{5,17}$

11. 强密码(必须包含大小写字母和数字的组合,不能使用特殊字符,长度在8-10之间):^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$

12. 日期格式:^\d{4}-\d{1,2}-\d{1,2}

13. 一年的12个月(01~09和1~12):^(0?[1-9]|1[0-2])$

14. 一个月的31天(01~09和1~31):^((0?[1-9])|((1|2)[0-9])|30|31)$

15. 钱的输入格式:

16. 1.有四种钱的表示形式我们可以接受:"10000.00" 和 "10,000.00", 和没有 "分" 的 "10000" 和 "10,000":^[1-9][0-9]*$

17. 2.这表示任意一个不以0开头的数字,但是,这也意味着一个字符"0"不通过,所以我们采用下面的形式:^(0|[1-9][0-9]*)$

18. 3.一个0或者一个不以0开头的数字.我们还可以允许开头有一个负号:^(0|-?[1-9][0-9]*)$

19. 4.这表示一个0或者一个可能为负的开头不为0的数字.让用户以0开头好了.把负号的也去掉,因为钱总不能是负的吧.下面我们要加的是说明可能的小数部分:^[0-9]+(.[0-9]+)?$

20. 5.必须说明的是,小数点后面至少应该有1位数,所以"10."是不通过的,但是 "10" 和 "10.2" 是通过的:^[0-9]+(.[0-9]{2})?$

21. 6.这样我们规定小数点后面必须有两位,如果你认为太苛刻了,可以这样:^[0-9]+(.[0-9]{1,2})?$

22. 7.这样就允许用户只写一位小数.下面我们该考虑数字中的逗号了,我们可以这样:^[0-9]{1,3}(,[0-9]{3})*(.[0-9]{1,2})?$

23 8.1到3个数字,后面跟着任意个 逗号+3个数字,逗号成为可选,而不是必须:^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,2})?$

24. 备注:这就是最终结果了,别忘了"+"可以用"*"替代如果你觉得空字符串也可以接受的话(奇怪,为什么?)最后,别忘了在用函数时去掉去掉那个反斜杠,一般的错误都在这里

25. xml文件:^([a-zA-Z]+-?)+[a-zA-Z0-9]+\\.[x|X][m|M][l|L]$

26. 中文字符的正则表达式:[\u4e00-\u9fa5]

27. 双字节字符:[^\x00-\xff] (包括汉字在内,可以用来计算字符串的长度(一个双字节字符长度计2,ASCII字符计1))

28. 空白行的正则表达式:\n\s*\r (可以用来删除空白行)

29. HTML标记的正则表达式:<(\S*?)[^>]*>.*?</\1>|<.*? /> (网上流传的版本太糟糕,上面这个也仅仅能部分,对于复杂的嵌套标记依旧无能为力)

30. 首尾空白字符的正则表达式:^\s*|\s*$或(^\s*)|(\s*$) (可以用来删除行首行尾的空白字符(包括空格、制表符、换页符等等),非常有用的表达式)

31. 腾讯QQ号:[1-9][0-9]{4,} (腾讯QQ号从10000开始)

32. 中国邮政编码:[1-9]\d{5}(?!\d) (中国邮政编码为6位数字)

33. IP地址:\d+\.\d+\.\d+\.\d+ (提取IP地址时有用)

34. IP地址:((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))

横竖屏判断


var updateOrientation =function(){
  if(window.orientation=='-90'|| window.orientation=='90'){
    console.log('为了更好的体验,请将手机/平板竖过来!');
   }else{
    console.log('竖屏状态');
  }
};
var supportsOrientationChange = "onorientationchange" in window,orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";// 监听事件
window.addEventListener(orientationEvent,updateOrientation);

获取 url 参数


function getParameterByName(name) {
	var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
	return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
}
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
function fGetQuery(name){
  var sUrl = window.location.search.substr(1);
  var r = sUrl.match(new RegExp("(^|&)" + name + "=([^&]*)(&|$)"));
  return (r == null ? null : (r[2]));
}

图片预加载


function loadImage(url, callback) {
  var img = new Image(); //创建一个Image对象,实现图片的预下载
  img.onload = function(){
    img.onload = null;
    callback(img);
  }
  img.src = url;
}

缓动算法


function easeIn(t,b,c,d){
	return c*(t/=d)*t + b;
}
function easeOut(t,b,c,d){
    return -c *(t/=d)*(t-2) + b;
}
function easeInOut(t,b,c,d){
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
}

获取键盘按键


function displayKeyCode(evt){
  var textBox = getObject('txtChar');
  var charCode = (evt.which) ? evt.which : event.keyCode
  textBox.value = String.fromCharCode(charCode);
  if (charCode == 8) textBox.value = "backspace"; //  backspace
  if (charCode == 9) textBox.value = "tab"; //  tab
  if (charCode == 13) textBox.value = "enter"; //  enter
  if (charCode == 16) textBox.value = "shift"; //  shift
  if (charCode == 17) textBox.value = "ctrl"; //  ctrl
  if (charCode == 18) textBox.value = "alt"; //  alt
  if (charCode == 19) textBox.value = "pause/break"; //  pause/break
  if (charCode == 20) textBox.value = "caps lock"; //  caps lock
  if (charCode == 27) textBox.value = "escape"; //  escape
  if (charCode == 33) textBox.value = "page up"; // page up
  if (charCode == 34) textBox.value = "page down"; // page down
  if (charCode == 35) textBox.value = "end"; // end
  if (charCode == 36) textBox.value = "home"; // home
  if (charCode == 37) textBox.value = "left arrow"; // left arrow
  if (charCode == 38) textBox.value = "up arrow"; // up arrow
  if (charCode == 39) textBox.value = "right arrow"; // right arrow
  if (charCode == 40) textBox.value = "down arrow"; // down arrow
  if (charCode == 45) textBox.value = "insert"; // insert
  if (charCode == 46) textBox.value = "delete"; // delete
  if (charCode == 91) textBox.value = "left window"; // left window
  if (charCode == 92) textBox.value = "right window"; // right window
  if (charCode == 93) textBox.value = "select key"; // select key
  if (charCode == 96) textBox.value = "numpad 0"; // numpad 0
  if (charCode == 97) textBox.value = "numpad 1"; // numpad 1
  if (charCode == 98) textBox.value = "numpad 2"; // numpad 2
  if (charCode == 99) textBox.value = "numpad 3"; // numpad 3
  if (charCode == 100) textBox.value = "numpad 4"; // numpad 4
  if (charCode == 101) textBox.value = "numpad 5"; // numpad 5
  if (charCode == 102) textBox.value = "numpad 6"; // numpad 6
  if (charCode == 103) textBox.value = "numpad 7"; // numpad 7
  if (charCode == 104) textBox.value = "numpad 8"; // numpad 8
  if (charCode == 105) textBox.value = "numpad 9"; // numpad 9
  if (charCode == 106) textBox.value = "multiply"; // multiply
  if (charCode == 107) textBox.value = "add"; // add
  if (charCode == 109) textBox.value = "subtract"; // subtract
  if (charCode == 110) textBox.value = "decimal point"; // decimal point
  if (charCode == 111) textBox.value = "divide"; // divide
  if (charCode == 112) textBox.value = "F1"; // F1
  if (charCode == 113) textBox.value = "F2"; // F2
  if (charCode == 114) textBox.value = "F3"; // F3
  if (charCode == 115) textBox.value = "F4"; // F4
  if (charCode == 116) textBox.value = "F5"; // F5
  if (charCode == 117) textBox.value = "F6"; // F6
  if (charCode == 118) textBox.value = "F7"; // F7
  if (charCode == 119) textBox.value = "F8"; // F8
  if (charCode == 120) textBox.value = "F9"; // F9
  if (charCode == 121) textBox.value = "F10"; // F10
  if (charCode == 122) textBox.value = "F11"; // F11
  if (charCode == 123) textBox.value = "F12"; // F12
  if (charCode == 144) textBox.value = "num lock"; // num lock
  if (charCode == 145) textBox.value = "scroll lock"; // scroll lock
  if (charCode == 186) textBox.value = ";"; // semi-colon
  if (charCode == 187) textBox.value = "="; // equal-sign
  if (charCode == 188) textBox.value = ","; // comma
  if (charCode == 189) textBox.value = "-"; // dash
  if (charCode == 190) textBox.value = "."; // period
  if (charCode == 191) textBox.value = "/"; // forward slash
  if (charCode == 192) textBox.value = "`"; // grave accent
  if (charCode == 219) textBox.value = "["; // open bracket
  if (charCode == 220) textBox.value = "\\"; // back slash
  if (charCode == 221) textBox.value = "]"; // close bracket
  if (charCode == 222) textBox.value = "'"; // single quote
  var lblCharCode = getObject('spnCode');
  lblCharCode.innerHTML = 'JavaScript KeyCode:  ' + charCode;
  return false;
}

简易的 Ready


function domReady(fn) {
  /in/.test(document.readyState) ? window.setTimeout(function() { domReady(fn); }, 10) :     fn();
}

ajax


//POST
var request = new XMLHttpRequest();
var data = "foo=bar&lorem=ipsum";
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.onreadystatechange = function() {//Call a function when the state changes.
  if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
    // Request finished. Do processing here.
  }
}
request.send(data);

//GET
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var resp = request.responseText;
  } else {
    // We reached our target server, but it returned an error
  }
};
request.onerror = function() {
  // There was a connection error of some sort
};
request.send();

XSS 过滤


function filterXSS(cont) {
	cont = cont.replace(/&/g, '&amp;');	//这里过滤&是为了让用户输入HTML实体时能展示成实体
	cont = cont.replace(/</g, '&lt;').replace(/>/g, '&gt;');
	cont = cont.replace(/\'/g, '&#39;').replace(/\"/g, '&quot;');
	return cont;

}

检测页面是否运行在 webview


/Safari\/\S+\s((?!Edge).)+/.test(navigator.userAgent) || /Mobile\/\S+\s((?!Safari).)+/.test(navigator.userAgent)

设备类型判断


function fBrowserRedirect(){
  var sUserAgent = navigator.userAgent.toLowerCase();
  var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
  var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
  var bIsMidp = sUserAgent.match(/midp/i) == "midp";
  var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
  var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
  var bIsAndroid = sUserAgent.match(/android/i) == "android";
  var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
  var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
}

debounce


function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	}
}
function debounce(fn, wait) {
  var timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, wait);
  };
}

throttle


function throttle(fn, wait) {
  var previous = 0;
  return function (...args) {
    var now = Date.now();
    if (now - previous >= wait) {
      fn.apply(this, args);
      previous = now;
    }
  };
}

检测返回

var hiddenProperty = 'hidden' in document ? 'hidden' :
    'webkitHidden' in document ? 'webkitHidden' :
    'mozHidden' in document ? 'mozHidden' :
    null;
var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
var onVisibilityChange = function(){
  if (document[hiddenProperty]) {
    console.log('页面非激活');
  }else{
    console.log('页面激活')
  }
}
document.addEventListener(visibilityChangeEvent, onVisibilityChange);

php

生成唯一序列号

function generateNum(){
  $charid = strtoupper(md5(uniqid(mt_rand(), true)));
  $uuid = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid,12, 4).substr($charid,16, 4).substr($charid,20,12);
  return $uuid;
}

插入到数组指定位置

function array_insert (&$array, $position, $insert_array) {
  $first_array = array_splice ($array, 0, $position);
  $array = array_merge ($first_array, $insert_array, $array);
}

红包算法

function getRedPackage($money, $num, $min, $max){
  $data = array();
  if ($min * $num > $money) {
    return array();
  }
  if($max*$num < $money){
    return array();
  }
  while ($num >= 1) {
    $num--;
    $kmin = max($min, $money - $num * $max);
    $kmax = min($max, $money - $num * $min);
    $kAvg = $money / ($num + 1);
    $kDis = min($kAvg - $kmin, $kmax - $kAvg);
    $r = ((float)(rand(1, 10000) / 10000) - 0.5) * $kDis * 2;
    $k = round($kAvg + $r);
    $money -= $k;
    $data[] = $k;
  }
  return $data;
}

yum 安装

//添加 epel 源
rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
//添加 remi 源
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
//安装
yum --enablerepo=remi,remi-php55 install php-fpm php-common php-devel php-mysqlnd php-mbstring php-mcrypt
//启动
service php-fpm start
//nginx配置
location ~ [^/]\.php(/|$) {
  try_files $uri =404;
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_index index.php;
  include fastcgi_params;
}
//修改fastcgi_params,添加
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO                $fastcgi_script_name;

判断是不是 url

<?php

define('URL_FORMAT',
'/^(https?)://'.                                         // protocol
'(([a-z0-9$_.+!*'(),;?&=-]|%[0-9a-f]{2})+'.         // username
'(:([a-z0-9$_.+!*'(),;?&=-]|%[0-9a-f]{2})+)?'.      // password
'@)?(?#'.                                                  // auth requires @
')((([a-z0-9].|[a-z0-9][a-z0-9-]*[a-z0-9].)*'.           // domain segments AND
'[a-z][a-z0-9-]*[a-z0-9]'.                                 // top level domain  OR
'|((d|[1-9]d|1d{2}|2[0-4][0-9]|25[0-5]).){3}'.
'(d|[1-9]d|1d{2}|2[0-4][0-9]|25[0-5])'.                 // IP address
')(:d+)?'.                                                // port
')(((/+([a-z0-9$_.+!*'(),;:@&=-]|%[0-9a-f]{2})*)*'. // path
'(?([a-z0-9$_.+!*'(),;:@&=-]|%[0-9a-f]{2})*)'.      // query string
'?)?)?'.                                                   // path and query string optional
'(#([a-z0-9$_.+!*'(),;:@&=-]|%[0-9a-f]{2})*)?'.      // fragment
'$/i');

/**
 * 判断URL
 *
 * @access public
 * @param $url 需要判断的字符串
 * @return 是不是url,true or false
 */
function is_valid_url($url) {
  if (str_starts_with(strtolower($url), 'http://localhost')) {
    return true;
  }
  return preg_match(URL_FORMAT, $url);
}


/**
 * String starts with something
 *
 * This function will return true only if input string starts with
 * niddle
 *
 * @param string $string Input string
 * @param string $niddle Needle string
 * @return boolean
 */
function str_starts_with($string, $niddle) {
  return substr($string, 0, strlen($niddle)) == $niddle;
}


/**
 * Test a URL for validity and count results.
 * @param url url
 * @param expected expected result (true or false)
 */

$numtests = 0;
$passed = 0;

function test_url($url, $expected) {
  global $numtests, $passed;
  $numtests++;
  $valid = is_valid_url($url);
  echo "URL Valid?: " . ($valid?"yes":"no") . " for URL: $url. Expected: ".($expected?"yes":"no").". ";
  if($valid == $expected) {
    echo "PASSn"; $passed++;
  } else {
    echo "FAILn";
  }
}

echo "URL Tests:nn";

test_url("http://localserver/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", true);
test_url("http://www.google.com", true);
test_url("http://www.google.co.uk/projects/my%20folder/test.php", true);
test_url("https://myserver.localdomain", true);
test_url("http://192.168.1.120/projects/index.php", true);
test_url("http://192.168.1.1/projects/index.php", true);
test_url("http://projectpier-server.localdomain/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", true);
test_url("https://2.4.168.19/project-pier?c=test&a=b", true);
test_url("https://localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", true);
test_url("http://user:password@localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", true);

echo "n$passed out of $numtests tests passed.nn";

?>

shell

mac 手动设置 ip 等

networksetup -setmanual Ethernet ip netmask gateway

添加静态路由

sudo route add -net 172.16.0.0 -netmask 255.255.0.0 -gateway 172.16.198.1

统计某一天访问量

awk '{print $1}' /var/log/access.log | sort | uniq | wc -l

删除 XX 时间之前的文件

//xx天之前
find /home/lifeccp/dicom/studies -mtime +21 -name "*.*" -exec rm -Rf {} \;
//xx分种之前
find /home/lifeccp/dicom/studies -mmin +21 -name "*.*" -exec rm -Rf {} \;

sql

给某个字段随机增加数字

UPDATE `tablename` SET `col1` = `col1` + floor(1000 + rand()* 500) WHERE `col2` = 1

批量替换

UPDATE `tablename` SET `col1` = replace(`col1`, 'str1', 'str2') WHERE

str1 为原始字符,str2 为替换后的字符

批量插入,重复不报错


主键已存在,不更改原纪录,只插入新的记录
INSERT IGNORE INTO

主键已存在,则替换原记录,即先删除原记录,后insert新记录
REPLACE INTO

主键已存在,则执行UPDATE更新操作
INSERT INTO ... ON DUPLICATE KEY UPDATE

查看表大小


select table_schema,concat(round(sum(data_length/1024/1024/1024),2),'GB') as data from tables GROUP BY TABLE_SCHEMA;

mysqldump带密码会报错

mysqldump -uroot -ppassword -R -E --all-databases --single-transaction > /tmp/mysql_backup.sql
mysqldump -h127.0.0.1 -P3306 -uroot -ppassword -R -E --all-databases --single-transaction > /cache/mysql_backup.sql
都会报以下错误:
mysqldump: Got error: 1698: "Access denied for user 'root'@'localhost'" when trying to connect
改成这样就好了
sudo mysqldump -uroot -ppassword -R -E --all-databases --single-transaction > /tmp/mysql_backup.sql

Python


 -*- coding: utf-8 -*-
 Python 2.7 学习参考脚本
 print 打印函数
 print "Hello World!"

导入数学模块
import math
math.sqrt(25)

导入一个函数
from math import sqrt
sqrt(25)  # 没必要再引用模块的名字了

一次导入多个函数
from math import cos, floor

引入模块中的所有函数(不建议)
from os import *

引入模块并起别名
import numpy as np

显示math模块下的所有函数
dir(math)

判断一个对象的类型
type(2)        # 返回 'int'
type(2.0)      # 返回 'float'
type('two')    # 返回 'str'
type(True)     # 返回 'bool'
type(None)     # 返回 'NoneType'

检查一个对象是什么类型
isinstance(2.0, int)   # 返回 False
isinstance(2.0, (int, float))  # 返回 True

转换数据类型
float(2)
int(2.9)
str(2.9)

0,None,和空容器转为False
bool(0)
bool(None)
bool('')   # 空字符串
bool([])   # 空列表(list)
bool({})   # 空字典(dictionary)

非空容器和非0转为True
bool(2)
bool('two')
bool([2])

Math
10 + 4    # 加法(14)
10 - 4    # 减法(6)
10 * 4    # 乘法(40)
10 ** 4   # 指数(10000)
10 / 4    # 除法(2, 因为两个数同为int类型)
10 / float(4)  # 除法(2.5)
5 % 4     # 求余(1)

在python 2.x 中强制做"真除法"(在Python 3.x中没有必要)
from __future__ import division  # 放在文件头
print 10 / 4   # 返回 2.5
10 // 4          # 返回 2

比较和bool运算
全部返回True
5 > 3
5 >= 3
5 != 3
5 == 5

bool 运算 全部返回True
5 > 3 and 6 > 3
5> 3 or 5 < 3
not False
False or not False and True  # 运算顺序为:not,and,or

控制语句

if 语句
x = 3
if x > 0:
	print '正数'

if/else 语句
if x > 0:
	print '正数'
else:
	print '<= 0'

if/elif/else 语句
if x > 0:
	print '正数'
elif x == 0:
	print '0'
else:
	print '负数'

if 语句,放在一行(不建议)
if x > 0: print '正数'
if/else 语句,放在一行 (不建议)
print '正数' if x > 0 else '<= 0'

列表list

创建一个空list (两种方法)
empty_list = []
empty_list = list()

创建一个list
simpsons = ['homer', 'marge', 'bart']

获取list元素
simpsons[0]
len(simpsons)   # 返回list长度(3)

修改list  (操作不会返回list)
simpsons.append('lisa')   # 在list尾插入元素  也可以append一个list
simpsons.extend(['itchy', 'scratchy'])  # 在list尾插入多个元素
simpsons.append(['itchy', 'scratchy'])  # 比较和extend的区别
simpsons.insert(0, 'maggie')     # 在0索引处插入元素(把所有东西向右移)
simpsons.remove('bart')          # 查找第一元素然后删除
simpsons.pop(0)                  # 删除索引为0的元素并返回
del simpsons[0]                  # 同上,但是不返回
simpsons[0] = 'krusty'	         # 替换索引0的元素

用+号拼接list(比extend方法慢)
neighbors = simpsons + ['ned', 'rod', 'todd']  # simpsons 不变

在list中查找元素
simpsons.count('lisa')   # 计算元素的个数
simpsons.index('itchy')  # 返回第一元素的索引

分割list [开始:结束:跨步]
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']
weekdays[0]      # 'mon'
weekdays[0:3]    # 'mon', 'tues', 'wed'
weekdays[:3]     # 'mon', 'tues', 'wed'
weekdays[3:]     # 'thurs', 'fri'
weekdays[-1]     # 'fri' 最后一个元素
weekdays[::2]    # 0,2,4   'mon' 'wed' 'fri'
weekdays[::-1]   # 倒序 (4, 3, 2, 1, 0)  'fri' 'thurs' 'wed' 'tues' 'mon'

倒序
list(reversed(weekdays))

在原地排序
simpsons.sort()
simpsons.sort(reverse=True)  # 倒序
simpsons.sort(key=len)       # 通过key排序

返回一个排过序的列表(不修改原始列表)
sorted(simpsons)
sorted(simpsons, reverse=True)
sorted(simpsons, key=len)

在排过序的列表中插入一个元素,并保持排序状态
num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)

创建同一个列表的引用
same_num = num
same_num[0] = 0      # 修改一个,same_sum 和 sum 一起改了

copy 一个列表(两种方法)
new_num = num[:]
new_num = list(num)

比较列表list
id(num) == id(same_num) # True
id(num) == id(new_num)  # False
num is same_num         # True
num is new_num          # False
num == same_num         # True
num == new_num          # True (他们的内容相同)


元组(Tuple)
和list相似,但是它不能改变大小

创建一个元组
digits = (0, 1, 'two')  # 创建一个元组
digits = tuple([0, 1, 'two'])  # 从list创建元组
zero = (0,)         # 逗号是必不可少的,它指定zero是一个元组,没有的话就是数字0了

访问元组数据
digits[2]   # 返回'two'
len(digits) #      3
digits.count(0)  # 0的个数 (1)
digits.index(1)  # 返回第一个1的索引(1)

元组里的元素不能修改
digits[2] = 2  # 抛出一个错误

拼接元组
digits = digits + (3, 4)

创建一个重复元素的元组(通常和list一起使用)
(3, 4) * 2   # 返回(3,4,3,4)

排序一个元组列表
tens = [(20,60), (10, 40), (20, 30)]
sorted(tens)   # 按元组里的第一个元素排序,第一个元素相同,比较第二个
               # [(10, 40), (20, 30), (20, 60)]

元组解包
bart = ('male', 10, 'simpson')
(sex, age, surname) = bart   # 一次符三个值

字符串

创建一个字符串
s = str(42)   # 把其它类型的数据转化为string
s = 'I like you'

提取string
s[0]    # 返回 'I'
len(s)  # 返回 10

分割字符串
s[:6]    # 'I like'
s[7:]    # 'you'
s[-1]    # 'u'

基本的string方法 (不修改原string)
s.lower()    # 'i like you'
s.upper()    # 'I LIKE YOU'
s.startswith('I')   # True
s.endswith('you')    # True
s.isdigit()         # False (Ture:数字组成的字符串)
s.find('like')      # 2 索引
s.find('hate')      # -1 没有找到
s.replace('lkie', 'love')  # 替换 'like' 为 'love'


分割字符串
s.split(' ')  # ['I','like','you']
s.split()     # 同上
s2 = 'a, an, the'
s2.split(',')   # ['a',' an',' the']

把列表中的字符串连成一个字符串
stooges = ['larry','curly','moe']
' '.join(stooges)     # 'larry curly moe'

连接字符串
s3 = 'The meaning of life is'
s4 = '42'
s3 + ' ' + s4
s3 + ' ' + str(42) # 'The meaning of life is 42'

移除字符串前后中的空白字符
s5 = '  ham and cheese  '
s5.strip()    # 'ham and cheese'

字符串替换
'raining %s and %s' % ('cat', 'dogs')    # 老方法
'raining {} and {}'.format('cats', 'dogs') # 新方法
'raining {arg1} and {arg2}'.format(arg1='cats', arg2='dogs')

字符串格式化
'pi is {:.2f}'.format(3.14159)   # 'pi is 3.14'

normal string 和 raw string
print 'first linensecond line'
print r'first linenfirst line'

字典(dictionaries)
由key-value对组成
key是唯一的,可以是string,数字,元组
values 可以是任何值

创建一个空字典(两种方法)
empty_dict = {}
empty_dict = dict()

创建一个字典(两种方法)
family = {'dad':'homer', 'mom':'marge', 'size':6}
family = dict(dad='homer', mom='marge', size=6)

把元组列表转化为字典
list_of_tuples = [('dad','homer'), ('mom','marge'), ('size', 6)]
family = dict(list_of_tuples)

获取字典元素
family['dad']   # 'homer'
len(family)     # 3
family.keys()   # ['dad', 'mom', 'size']
family.values() # ['homer', 'marge', 6]
family.items()  # [('dad', 'homer'), ('mom', 'marge'), ('size', 6)]
'mom' in family # Ture
'marge' in family # False (只判断key)

修改字典
family['cat'] = 'snowball'  # 增加一个新纪录
family['cat'] = 'snowball ii' # 编辑一个以存在的记录
del family['cat']         # 删除一个记录
family['kids'] = ['bart', 'lisa']  # 值可以是列表
family.pop('dad')          # 删除一个记录并返回值
family.update({'baby':'maggie', 'grandpa':'abe'}) # 增加多个记录

family['mom']   # 'marge'
family.get('mom') # 同上
#family['grandma']  # 抛出错误
family.get('grandma')  # 返回None
family.get('grandma', 'not found')  # 'not found'

family['kids'][0]   # 'bart'
family['kids'].remove('lisa')   # 移除'lisa'

用字典替换字符串
'youngest child is %(baby)s' % family   # 'youngest child is maggie'

set
无重复集合

创建空set
empty_set = set()

创建集合
languages = {'python', 'r', 'java'}
snakes = set(['cobra', 'viper', 'python'])

len(languages)  # 3
'python' in languages   # True

set 操作
languages & snakes # 两个集合的交集  {'python'}
languages | snakes # 联合   {'cobra', 'r', 'java', 'viper', 'python'}
languages - snakes # {'r', 'java'}
snakes - languages # {'cobra', 'viper'}

修改集合
languages.add('sql')   # 增加一个元素
languages.add('r')     # 试图增加一个以存在的元素,忽略,没有错误
languages.remove('java') # 移除一个元素
languages.remove('c')    # 试图移除一个不存在的元素,抛出错误
languages.discard('c')   # 移除一个存在的元素,如果不存在,忽略
languages.pop()          # 移除并返回元素
languages.clear()        # 清空集合
languages.update('go', 'spark') # 增加多个元素

排序
sorted(set([9, 0, 2, 1, 0]))  # [0, 1, 2, 9]   去重排序

定义函数

定义一个没有参数和返回值的函数
def print_text():
	print 'you are dumb'

调用一个函数
print_text()

定义一个有一个参数没有返回值的函数
def print_this(x):
	print x

调用
print_this(4)  # 4
n = print_this(4)  # 打印4,但是不会给n赋值

定义一个一个参数和返回值的函数
def square_this(x):
	return x ** 2

带函数描述
def square_this(x):
	""" Return the square of number."""
	return x ** 2

square_this(3)
var = square_this(3) # var = 9

带默认参数的函数
def calc(a, b, op='add'):
	if op == 'add':
		return a + b
	elif op == 'sub':
		return a -b
	else:
		print 'no op'

调用
calc(10, 4, op='add')   # 14
calc(10, 4, 'add')      # 14
calc(10, 4)             # 14
calc(10, 4, 'sub')      # 6
calc(10, 4, 'div')      # 'no op'

用 pass 写一个没有函数体的函数,它只是一个占位符
def stub():
	pass

一个函数返回2个值
def min_max(nums):
	return min(nums), max(nums)

nums = [1, 2, 3]
min_max_num = min_max(nums)  #  min_max_num = (1,3)  元组
min_num, max_num = min_max(nums) # min_num = 1,max_num = 3,  元组解包

匿名函数(Lambda)

普通方式定义函数
def squared(x):
	return x ** 2

lamba
squared = lambda x : x ** 2

通过最后的字符排列字符串(不用lambda)
simpsons = ['homer', 'marge', 'bart']
def last_letter(word):
	return word[-1]
sorted(simpsons, key=last_letter)

用lambda
sorted(simpsons, key=lambda word : word[-1])

For 循环和 while循环

range 返回整数列表
range(0, 3)   # [0, 1, 2]
range(3)      # 同上
range(0, 5, 2) # [0, 2, 4]  # 第三个参数跳跃

for 循环(不建议)
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
	print fruits[i].upper()

建议
for fruit in fruits:
	print fruit.upper()

用 xrange 避免遍历大数组时创建 整数数组
for i in xrange(10 ** 6):
	pass

用元组解包一次遍历两个东西
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
	print key, value

用枚举 如果你想在循环中用索引
for index, fruit in enumerate(fruits):
	print index, fruit

for/else 循环
for fruit in fruits:
	if fruit == 'banana':
		print "I like banana"
		break
else:    # 只用当代码没有执行break时
	print "Can't find the banana"

while 循环
count = 0
while count < 5:
	print count
	count += 1

例子
nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
	cubes.append(num ** 3)

等价 comprehension
cubes = [num**3 for num in nums]

cubes_of_even = []
for num in nums:
	if num % 2 == 0:
		cubes_of_even.append(num**3)
等价 comprehension
cubes_of_even = [num**3 for num in nums if num % 2 == 0]

cubes_add_squares = []
for num in nums:
	if num % 2 == 0:
		cubes_add_squares.append(num**3)
	else:
		cubes_add_squares.append(num**2)
等价 comprehension
cubes_and_squares = [num**3 if num % 2 == 0 else num**2 for num in nums]

matrix = [[1, 2], [3, 4]]
items = []
for row in matrix:
    for item in row:
        items.append(item)
等价 comprehension
items = [item for row in matrix
              for item in row]

set comprehension
fruits = ['apple', 'banana', 'cherry']
unique_lengths = {len(fruit) for fruit in fruits}   # {5, 6}

dictionary comprehension
fruit_lengths = {fruit:len(fruit) for fruit in fruits}              # {'apple': 5, 'banana': 6, 'cherry': 6}
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)} # {'apple': 0, 'banana': 1, 'cherry': 2}


map reduce  filter

map'把一个操作应用到所有元素上
simpsons = ['homer', 'marge', 'bart']
map(len, simpsons)   # 求每个元素的长度 [5, 5, 4]
map(lambda word: word[-1], simpsons)  # ['r', 'e', 't']
等价
[len(word) for word in simpsons]
[word[-1] for word in simpsons]


先把前两个元素执行某个函数,求的结果,依次计算
reduce(lambda x,y: x + y, range(4)  # (((0+1)+2)+3) = 6

用指定函数过滤
filter(lambda x: x % 2 == 0, range(5))  # [0, 2, 4]

while True:
	for i in ['/', '-', '|', '\\', '|']:
		print "%s\r" % i,