Giter Site home page Giter Site logo

-work_tip's People

Contributors

shenglian avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

huyunzhen

-work_tip's Issues

[小程式] 拉分割視窗

<div id="container">
    <!-- Left side -->
    <div id="left"> This is the left side's content! </div>
    <!-- Right side -->
    <div id="right">
        <!-- Actual resize handle -->
        <div id="handle"></div> This is the right side's content!
    </div>
</div>
body, html {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}
#container {
    width: 100%;
    height: 100%;
    /* Disable selection so it doesn't get annoying */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: moz-none;
    -ms-user-select: none;
    user-select: none;
}
#container #left {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 100px;
    background: red;
}
#container #right {
    position: absolute;
    right: 0;
    top: 0;
    bottom: 0;
    width: 200px;
    background: blue;
}
#container #handle {
    position: absolute;
    left: -4px;
    top: 0;
    bottom: 0;
    width: 8px;
    cursor: w-resize;
}
var isResizing = false,
    lastDownX = 0;

$(function () {
    var container = $('#container'),
        left = $('#left'),
        right = $('#right'),
        handle = $('#handle');

    handle.on('mousedown', function (e) {
        isResizing = true;
        lastDownX = e.clientX;
    });

    $(document).on('mousemove', function (e) {
        // we don't want to do anything if we aren't resizing.
        if (!isResizing) 
            return;
        
        var offsetRight = container.width() - (e.clientX - container.offset().left);

        left.css('right', offsetRight);
        right.css('width', offsetRight);
    }).on('mouseup', function (e) {
        // stop resizing
        isResizing = false;
    });
});

[css] aspect Ratio

<div class="embed-responsive embed-responsive-16by9">
  <video src="https://www.w3schools.com/html/mov_bbb.mp4"></video>
</div>
.embed-responsive {
  position: relative;
  display: block;
  height: 0;
  padding: 0;
  overflow: hidden;
}

.embed-responsive .embed-responsive-item,
.embed-responsive iframe,
.embed-responsive embed,
.embed-responsive object,
.embed-responsive video {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}

.embed-responsive-16by9 {
  padding-bottom: 56.25%;
}

.embed-responsive-3by2 {
  padding-bottom: 66.66%;
}

.embed-responsive-8by5 {
  padding-bottom: 62.5%;
}

.embed-responsive-4by3 {
  padding-bottom: 75%;
}

[js] form vaild

var isExisty = function (value) {
  return value !== null && value !== undefined;
};

var isEmpty = function (value) {
  return value === '';
};

var validations = {
  isDefaultRequiredValue: function (values, value) {
    return value === undefined || value === '';
  },
  isExisty: function (values, value) {
    return isExisty(value);
  },
  matchRegexp: function (values, value, regexp) {
    return !isExisty(value) || isEmpty(value) || regexp.test(value);
  },
  isUndefined: function (values, value) {
    return value === undefined;
  },
  isEmptyString: function (values, value) {
    return isEmpty(value);
  },
  isEmail: function (values, value) {
    return validations.matchRegexp(values, value, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i);
  },
  isUrl: function (values, value) {
    return validations.matchRegexp(values, value, /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i);
  },
  isTrue: function (values, value) {
    return value === true;
  },
  isFalse: function (values, value) {
    return value === false;
  },
  isNumeric: function (values, value) {
    if (typeof value === 'number') {
      return true;
    }
    return validations.matchRegexp(values, value, /^[-+]?(?:\d*[.])?\d+$/);
  },
  isAlpha: function (values, value) {
    return validations.matchRegexp(values, value, /^[A-Z]+$/i);
  },
  isAlphanumeric: function (values, value) {
    return validations.matchRegexp(values, value, /^[0-9A-Z]+$/i);
  },
  isInt: function (values, value) {
    return validations.matchRegexp(values, value, /^(?:[-+]?(?:0|[1-9]\d*))$/);
  },
  isFloat: function (values, value) {
    return validations.matchRegexp(values, value, /^(?:[-+]?(?:\d+))?(?:\.\d*)?(?:[eE][\+\-]?(?:\d+))?$/);
  },
  isWords: function (values, value) {
    return validations.matchRegexp(values, value, /^[A-Z\s]+$/i);
  },
  isSpecialWords: function (values, value) {
    return validations.matchRegexp(values, value, /^[A-Z\s\u00C0-\u017F]+$/i);
  },
  isLength: function (values, value, length) {
    return !isExisty(value) || isEmpty(value) || value.length === length;
  },
  equals: function (values, value, eql) {
    return !isExisty(value) || isEmpty(value) || value == eql;
  },
  equalsField: function (values, value, field) {
    return value == values[field];
  },
  maxLength: function (values, value, length) {
    return !isExisty(value) || value.length <= length;
  },
  minLength: function (values, value, length) {
    return !isExisty(value) || isEmpty(value) || value.length >= length;
  }
};

module.exports = validations;

[Vue] 響應式

<pre id="test"></pre>
function Observer(obj, key, value){
  var dep = new Dep();
  
  if (Object.prototype.toString.call(value) == '[object Object]') {
    Object.keys(value).forEach(function(key){
      new Observer(value,key,value[key])
    })
  }

  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function(){
      if (Dep.target) {
        dep.addSub(Dep.target);
      };
      return value;
    },
    set: function(newVal){
      value = newVal;
      dep.notify();
    }
  })
}

function Watcher(fn){
  this.update = function(){
    Dep.target = this;
    fn();
    Dep.target = null;
  }
  this.update();
}

function Dep(){
  this.subs = [];
  
  this.addSub = function (watcher) {
    this.subs.push(watcher);
  }

  this.notify = function(){
    this.subs.forEach(function(watcher){
      watcher.update();
    });
  }
}

var obj = {
  a: 1,
  b: 2,
};

Object.keys(obj).forEach(function(key){
  new Observer(obj, key, obj[key])
});

new Watcher(function(){
  document.querySelector("#test").innerHTML = obj.a;
});

[js] webAudio

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <title>Web Audio</title>
    </head>

    <body>
        <canvas id="myCanvas" width="400" height="400">您的浏览器不支持canvas标签</canvas>
        <audio id="myAudio" src="./Tokyo_Ghoul_Alone.mp4" controls="controls" >您的浏览器不支持audio标签</audio>
        <script type="text/javascript">
            (function(w, d){
                try {
                    var audioCtx = new (w.AudioContext || w.webkitAudioContext)();
                } catch (err) {
                    alert('!Your browser does not support Web Audio API!');
                };
                var myCanvas = d.getElementById('myCanvas'),
                    canvasCtx = myCanvas.getContext("2d"),
                    myAudio = d.getElementById("myAudio"),
                    source = audioCtx.createMediaElementSource(myAudio),
                    analyser = audioCtx.createAnalyser();
                    
                    source.connect(analyser);
                    analyser.connect(audioCtx.destination);
                    myAudio.oncanplaythrough = function draw () {
                        var cwidth = myCanvas.width,
                            cheight = myCanvas.height,
                            array = new Uint8Array(128);
                        analyser.getByteFrequencyData(array);
                        canvasCtx.clearRect(0, 0, cwidth, cheight);
                        
                        for (var i = 0; i < array.length; i++) {
                            canvasCtx.fillRect(i * 3, cheight - array[i], 1, cheight);
                            // x, y, w, h
                        }
                    requestAnimationFrame(draw);
                };
            })(window, document);
        </script>
    </body>
</html>

[js] bind event listen use for loop Raw

// 要綁定的名稱
var arr = [
  'div1',
  'div2',
  'div3'
];

for(var i = 0; i < arr.length; i++){
  bindEventListeners(arr[i])
}

function bindEventListeners(ids){
  var ids = document.querySelector(ids);
  ids.addEventListener('click', function(e){
    // doSomething...
  })
}

[scss] Css Responsive Square and Rectangle

// Css Responsive Square and Rectangle
@mixin square($size, $scale){
	position: relative;
	width: $size + %;  				/* desired width */
	&:before {
		content: "";
		display: block;
		padding-top: $scale + %;        /* initial ratio */
	}
}

[css] 解決頁面 iOS上滑動卡頓的問題

/* 
1. 在我們針對iPad或iPhone等iDevice作最佳化的設計時,
每每當頁面中包含有iFrame或者是某個區塊設定了固定高度,
讓這個區塊自行使用捲軸時,
那麼這時候,當我們去使用這個內部捲軸時,
都會很不順,有時根本無作用。
2. 啟用了硬件加速特性 
3. Safari真的用了原生控件來實現,
對於有-webkit-overflow-scrolling的網頁,
會創建一個UIScrollView,
提供子layer給渲染模塊使用。
*/ 
-webkit-overflow-scrolling: touch;

[python] crawler

#-*- coding:utf-8 -*-
# 要先安裝 requests, BeautifulSoup
import requests
from bs4 import BeautifulSoup

# 頁面解析的方式
HTML_PARSER = "html.parser"
# 要爬的網址
crawel_url = 'http://www.gomaji.com/index.php?ch=8'


def getData():
    r = requests.get(crawel_url)
    r.encoding = 'utf-8'

	if r.status_code == requests.codes.ok:
		content = BeautifulSoup(r.content, HTML_PARSER)
		
	        # 這邊要去看 BeautifulSoup 的 api 拿取 dom 的方式 
        	# => http://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/
		shop_links_a_tags = content.find_all('h2', attrs={'class': 'ref_name_2'})

        	# shop_links_a_tags 抓出來之後,是一個 python list 的物件,直接 print 出來會呈現 unicode,所以要用 for loop print 出來
		for link in shop_links_a_tags:
			print link

	else:
		print 'fail'

getData()

[scss] center of text

// 文字置中
@mixin textCenter($height){
  height: $height;
  line-height: $height;    
  text-align: center;
} 

[scss]

$z-layers: (
	"sidebar": 10000,
	"sidebar-overlay": 9999
);

// 針對 Cupoy Moblie 的 Z index 做設定
@function z($zindex) {
	@if not map-has-key($z-layers, $zindex){
		@warn "No z-index found for '#{$zindex}' in z-layers map!"
	}
	@return map-get($z-layers,  $zindex);
}

[小程式] 純 css 寬度縮小為 ...

網址

<div class="demo">
  <input type="checkbox" id="WidthTogglerHeader">
  <label for="WidthTogglerHeader">拖动下面容器或选择复选框</label>
  <div class="wrapper">
    <div class="overflower">
      <div class="overflower-short">我是短文字我是短文字</div>
      <div class="overflower-long">真的可以把长的文本变成短的文本</div>
    </div>
  </div>
</div>
body {
  height: 100vh;
  display: flex;
}

.demo {
  width: 556px;
  margin: auto;
}

.wrapper {
  overflow: hidden;
  text-align: center;
  width: 100%;
  padding: 0.5em 1em;
  border: 1px solid;
  transition: width 1.5s;
  margin-top: 10px;
}

.overflower {
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
  /* max-width: 100%; */
  height: 1.5em;
  line-height: 1.5em;
  white-space: nowrap;
  text-overflow: ellipsis;
  .overflower-short {
    overflow: hidden;
    flex-grow: 1;
    width: 0;
    text-overflow: ellipsis;
  }

  .overflower-long {
    flex-basis: 100%;
  }
}

:checked + label + .wrapper {
  width: 20% !important;
}

[scss] triangle

// 三角形基本樣式
%basic-triangle-type {
	content: '';
	position: absolute;
	width: 0px;
	height: 0px;
	border-style: solid;
	z-index: 10;	
}

// 三角形基本樣式 (上下左右)
@mixin triangle-up($color,$top,$left,$width,$height) {
	@extend %basic-triangle-type; 
	top: $top;
	left: $left;
	border-width: 0 $width $height $width;
	border-color: transparent transparent $color transparent;	
}

@mixin triangle-down($color,$top,$left,$width,$height) {
	@extend %basic-triangle-type; 
	top: $top;
	left: $left;
	border-width: $height $width 0 $width;
	border-color: $color transparent transparent transparent;
}

@mixin triangle-right($color,$top,$left,$width,$height) {
	@extend %basic-triangle-type; 
	top: $top;
	left: $left;
	border-width: $width 0 $width $height;
	border-color: transparent transparent transparent $color; 	
}

@mixin triangle-lef($color,$top,$left,$width,$height) {
	@extend %basic-triangle-type; 
	top: $top;
	left: $left;
	border-width: $width $height $width 0;
	border-color: transparent $color transparent transparent;	
}

[小程式] 製作 input range

<div>50</div>
<input type="range" />
<button id="increase">increase button</button>
<button id="decrease">decrease button</button>
input[type=range]{
  -webkit-appearance: none;
  background: none;
}

input[type=range]::-webkit-slider-runnable-track {
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}

input[type=range]::-ms-track {
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}

input[type=range]::-moz-range-track {
  height: 5px;
  background: #ddd;
  border: none;
  border-radius: 3px;
}

input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #555;
  margin-top: -5px;
  position: relative;
}

input[type=range]::-ms-thumb {
  -webkit-appearance: none;
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #555;
  margin-top: -5px;
  position: relative;
}

input[type=range]::-moz-range-thumb {
  -webkit-appearance: none;
  border: none;
  height: 16px;
  width: 16px;
  border-radius: 50%;
  background: #555;
  margin-top: -5px;
  position: relative;
}

input[type=range]:focus {
  outline: none;
  &::-webkit-slider-thumb:after {
    position: absolute;
    top: -35px;
    left: 50%;
    transform: translateX(-50%);
    background: #eee;
    border-radius: 5px;
    color: #555;
    padding: 5px 10px;
    border: 2px solid #555;
  }
  &::-ms-thumb:after {
    position: absolute;
    top: -35px;
    left: 50%;
    transform: translateX(-50%);
    background: #eee;
    border-radius: 5px;
    color: #555;
    padding: 5px 10px;
    border: 2px solid #555;
  }
  &::-moz-range-thumb:after {
    position: absolute;
    top: -35px;
    left: 50%;
    transform: translateX(-50%);
    background: #eee;
    border-radius: 5px;
    color: #555;
    padding: 5px 10px;
    border: 2px solid #555;
  }
}

input[type=range]:focus::-webkit-slider-runnable-track {
  background: #ccc;
}

input[type=range]:focus::-ms-track {
  background: #ccc;
}

input[type=range]:focus::-moz-range-track {
  background: #ccc;
}
var rng = document.querySelector("input");
var add = document.getElementById("increase");
var cut = document.getElementById("decrease");

read("mousedown");
read("mousemove");

function read(evtType) {
  rng.addEventListener(evtType, function() {
    window.requestAnimationFrame(function() {
      document.querySelector("div").innerHTML = rng.value;
    });
  });
}

add.addEventListener('click', function() {
  rng.value++;
  window.requestAnimationFrame(function() {
    document.querySelector("div").innerHTML = rng.value;
  });
});

cut.addEventListener('click', function() {
  rng.value--;
  window.requestAnimationFrame(function() {
    document.querySelector("div").innerHTML = rng.value;
  });
});

[css] 修改 Chrome text size 默認配置

// 禁用Webkit內核瀏覽器的文字大小調整功能。
html { -webkit-text-size-adjust: none; }
// 打開縮放功能,則定義下面的全局樣式
* { -webkit-text-size-adjust:auto !important; }

[js] requestAnimationFrame

<div id ="container">
<div id ="animate"></div>
</div>
#container {
  width: 400px;
  height: 50px;
  position: relative;
  background: yellow;
}
#animate {
  width: 50px;
  height: 50px;
  position: absolute;
  background-color: red;
}
var elem = document.getElementById("animate"); 
var left = 0;
var bound = false;
  
requestAnimationFrame(Move);

function Move() {
  if(left === 0 || left === 350) {
    bound = !bound;
  }
  (bound) ? left++ : left--;
  elem.style.left = left + 'px'; 
  window.requestAnimationFrame(Move);
}

[小程式]使用JavaScript 写Web路由

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Building a router</title>

  <script>
    // Put John's template engine code here...
    // Simple JavaScript Templating
    // John Resig - https://johnresig.com/ - MIT Licensed
    (function () {
      var cache = {};

      this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ?
          cache[str] = cache[str] ||
          tmpl(document.getElementById(str).innerHTML) :

          // Generate a reusable function that will serve as a template
          // generator (and which will be cached).
          new Function("obj",
            "var p=[],print=function(){p.push.apply(p,arguments);};" +

            // Introduce the data as local variables using with(){}
            "with(obj){p.push('" +

            // Convert the template into pure JavaScript
            str
            .replace(/[\r\t\n]/g, " ")
            .split("<%").join("\t")
            .replace(/((^|%>)[^\t]*)'/g, "$1\r")
            .replace(/\t=(.*?)%>/g, "',$1,'")
            .split("\t").join("');")
            .split("%>").join("p.push('")
            .split("\r").join("\\'") +
            "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
      };
    })();

    (function () {
      var routes = {};  // A hash to store our routes:
      var events = [];  // An array of the current route's events:
      var el = null;    // The element where the routes are rendered:
      var ctx = {       // Context functions shared between all controllers:
        on: function (selector, evt, handler) {
          events.push([selector, evt, handler]);
        },
        refresh: function (listeners) {
          listeners.forEach(function (fn) {
            fn();
          });
        }
      };

      // Defines a route:
      function route(path, templateId, controller) {
        if (typeof templateId === 'function') {
          controller = templateId;
          templateId = null;
        }

        var listeners = [];

        Object.defineProperty(controller.prototype, '$on', {
          value: ctx.on
        });

        Object.defineProperty(controller.prototype, '$refresh', {
          value: ctx.refresh.bind(undefined, listeners)
        });

        routes[path] = {
          templateId: templateId,
          controller: controller,
          onRefresh: listeners.push.bind(listeners)
        };
      }

      function forEachEventElement(fnName) {
        for (var i = 0, len = events.length; i < len; i++) {
          var els = el.querySelectorAll(events[i][0]);
          for (var j = 0, elsLen = els.length; j < elsLen; j++) {
            els[j][fnName].apply(els[j], events[i].slice(1));
          }
        }
      }

      function addEventListeners() {
        forEachEventElement('addEventListener');
      }

      function removeEventListeners() {
        forEachEventElement('removeEventListener');
      }

      function router() {        
        el = el || document.getElementById('view'); // Lazy load view element:
        
        removeEventListeners();                     // Remove current event listeners:
        events = [];                                // Clear events, to prepare for next render:

        var url = location.hash.slice(1) || '/';    // Current route url (getting rid of '#' in hash as well):
        var route = routes[url] || routes['*'];     // Get route by url or fallback if it does not exist:
        
        if (route && route.controller) {            // Do we have a controller:
          var ctrl = new route.controller();
          if (!el || !route.templateId) {
            // If there's nothing to render, abort:
            return;
          }
          // Listen on route refreshes:
          route.onRefresh(function () {
            removeEventListeners();
            // Render route template with John Resig's template engine:
            el.innerHTML = tmpl(route.templateId, ctrl);
            addEventListeners();
          });
          // Trigger the first refresh:
          ctrl.$refresh();
        }
          
        if (el && route.controller) { // 使用John Resig的模板引擎,渲染路由模板 
          el.innerHTML = tmpl(route.templateId, new route.controller()); 
        }
      }
      
      this.addEventListener('hashchange', router);  // Listen on hash change:
      this.addEventListener('load', router);        // Listen on page load:
      
      this.route = route;                           // Expose the route register function:
    })();
  </script>

  <script type="text/html" id="home">
    <h1>Router FTW!</h1>
  </script>
  <script type="text/html" id="template1">
    <h1>Page 1: <%= greeting %>
    </h1>
    <p><%= moreText %></p>
    <button class="my-button">Click me <%= counter %> </button>
  </script>
  <script type="text/html" id="template2">
    <h1>Page 2: <%= heading %></h1>
    <p>Lorem ipsum...</p>
  </script>
  <script type="text/html" id="error404">
    <h1>404 Not found</h1>
  </script>

</head>

<body>
  <article>
    <a href="https://www.w3cplus.com/javascript/a-javascript-router.html"> 使用JavaScript 写Web路由 </a>
  </article>
  
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#/page1">Page 1</a></li>
    <li><a href="#/page2">Page 2</a></li>
  </ul>

  <div id="view"></div>
  <script>
    route('/', 'home', function () {});
    route('/page1', 'template1', function () {
      this.greeting = 'Hello world!';
      this.moreText = 'Bacon ipsum...';
      this.counter = 0;
      this.$on('.my-button', 'click', function () {
        this.counter += 1;
        this.$refresh();
      }.bind(this));
    });
    route('/page2', 'template2', function () {
      this.heading = 'I\'m page two!';
    });
    route('*', 'error404', function () {});
  </script>
</body>

</html>

[小程式] 控制裝置陀螺儀 ( 三軸 )

deviceorientation.js

(function(w, d){
	if(w.DeviceOrientationEvent) {
		
		var svgElement = document.querySelector('svg');
		var maskedElement = document.querySelector('#mask-circle');
		var circleFeedback = document.querySelector('#circle-shadow');
		var svgPoint = svgElement.createSVGPoint();

		w.addEventListener('deviceorientation', function(event){
			// 判斷 IOS 
			if(event.webkitCompassHeading) {
				var alpha = event.webkitCompassHeading;
			} else {
				var alpha = event.alpha;
			}
			
			var beta = event.beta;
		 	var gamma = event.gamma;

		}, false);
	} else {
		d.querySelector('body').innerHTML = '你的瀏覽器不支援喔';
	}
})(window, document);
(function(w, d){
	if(w.DeviceOrientationEvent) {
		var _x = d.getElementById('x');
		var _y = d.getElementById('y');
		var _z = d.getElementById('z');

		var svgElement = document.querySelector('svg');
		var maskedElement = document.querySelector('#mask-circle');
		var circleFeedback = document.querySelector('#circle-shadow');
		var svgPoint = svgElement.createSVGPoint();

		function cursorPoint(e, svg) {
		    svgPoint.x = e.clientX;
		    svgPoint.y = e.clientY;
		    return svgPoint.matrixTransform(svg.getScreenCTM().inverse());
		}

		function autoUpdate(y){
			maskedElement.setAttribute('y', y);
		}

		w.addEventListener('deviceorientation', function(event){
			// 判斷 IOS 
			if(event.webkitCompassHeading) {
				var alpha = event.webkitCompassHeading;
			} else {
				var alpha = event.alpha;
			}
			
			var beta = event.beta;
		 	var gamma = event.gamma;

		 	// _x.innerHTML =  alpha;
		 	// _y.innerHTML =  beta;
		 	// _z.innerHTML =  gamma;

		 	autoUpdate(Math.round(beta)*3);

		}, false);
	} else {
		d.querySelector('body').innerHTML = '你的瀏覽器不支援喔';
	}
})(window, document);
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <title>Mobile Deviceorientation Demo</title>
    </head>
    <style>
        html,
        body {
          height: 100%;
          margin: 0;
        }
        body {
          font-family: Monaco;
          font-size: 12px;
          color: rgba(0,0,0,.7);
        }
        svg {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: block;
          width: 100%;
          height: 100%;
        }
        div,
        a {
          position: relative;
          padding: 1em;
        }
        div {
          text-shadow: 0 1px 0 rgba(255,255,255,.5);
        }
        span {
          color: rgba(0,0,0,.4);
        }
        a {
          color: rgba(255,0,0,.5);
        }
    </style>

    <body>
        <!-- <div>YOYO</div>
        alpha: <div id="x"></div><br />
        beta: <div id="y"></div><br />
        gamma: <div id="z"></div><br /> -->

        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">
            <image xmlns:xlink= "http://www.w3.org/1999/xlink" xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/a.svg" width="100%" height="100%" />
        </svg>

        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink= "http://www.w3.org/1999/xlink">
            <defs>
                <clipPath id="mask">
                    <rect id="mask-circle" x="0" y="0" width="100%" height="100" style="fill:rgb(0,0,255);"/>
                </clipPath>
            </defs>
            <g clip-path="url(#mask)">
                <rect width="100%" height="100%" fill="#272730"/>
                <image xmlns:xlink= "http://www.w3.org/1999/xlink" xlink:href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9473/b.svg" width="100%" height="100%" />
            </g>
        </svg>

        <script src="./easy_application.js"></script>
    </body>
</html>

[js] modify image width/height

(function() {
  var maxWidth = 200,
      maxHeight = 300,
      maxRatio = maxWidth / maxHeight;
  
  var image = new Image();
  
  image.onload = function() {
    var oWidth = this.width,
        oHeight = this.height,
        ratio = oWidth / oHeight,
        width,
        height;
    
    console.log(ratio)
    
    if(ratio > maxRatio) {
      width = oWidth * maxHeight / oHeight;
      height = maxHeight;
    }
    else {
      width = maxWidth;
      height = oHeight * maxWidth / oWidth;
    }
  
    this.width = width;
    this.height = height;
  
    document.body.appendChild(this);
  };
  
  image.src = 'https://unsplash.imgix.net/photo-1434139240289-56c519f77cb0?dpr=2&fit=crop&fm=jpg&q=75&w=1050';
})();

String Api

charAt
charCodeAt
codePointAt

substring
substr
slice
split

indexOf
lastIndexOf

search
match
replace => return new string

toLowerCase
toUpperCase

concat

endsWith
startWith

IE not surpport
repeat
includes

[js] Esc

if(e.which == 27){
  // console.log('todo something');
}

各篇文章讀後心得前言

來源:mqyqingfeng/Blog#17

其實我也跟這位作者有一樣的想法。
雖然,我也一直都在學東西,也是都感覺都再學一堆 API 而已。
工作越久,越有這種感覺 ...

我想每隔一段時間,
應該都要再去把底層複習一遍。

大綱:

原型到原型鏈
詞法作用域和動態作用域
執行上下文
變量對象
作用域鏈
從 ECMAScript 的規範解讀 this
閉包
參數按值傳遞
call and apply 的模擬實現
bind 的模擬實現
new 的模擬實現
類數組對象與 arguments
創建對象的多種方式以及優缺點
繼承的多種方式以及優缺點

[scss] gap of text

// 文字上下間距一樣
@mixin textHeightCenter($height){
  height: $height;
  line-height: $height;    
} 

[css] flex-grow/flex-shrink/flex-basis

網址

flex-grow : 分配增加剩餘空間
flex-shrink : 分配剪掉多餘空間
flex-basis : 設定基本值

<ul>
  <li>123</li>
  <li>456</li>
  <li>789</li>
</ul>
/*
測試 flex-wrap, flex-grow, flex-basis
當寬度不夠放入 flex-basis 時,會轉到下一行(flex-wrap: wrap)。
*/
ul, li {
  margin: 0;
  padding: 0;
}

ul {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 50px;
  li {
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;  // grow 1 / shrink 1 / basis 0%
    background-color: #333;
    font-size: 13px;
    color: #fff;
    &:nth-child(1) { flex-basis: 100px; background-color: #9b9b9b;}
    &:nth-child(2) { flex-basis: 200px; background-color: #4a4a4a;}
    &:nth-child(3) { flex-basis: 300px; background-color: #333333;}
  }
}

[js] class static methods

class Triple {
    static triple(n) {
        n = n || 1;
        return n * 3;
    }
}

class BiggerTriple extends Triple {
    static triple(n) {
        return super.triple(n) * super.triple(n);
    }
}

console.log(Triple.triple());
console.log(Triple.triple(6));
console.log(BiggerTriple.triple(3));

[js] scrollTo every where

// 無限往下走
window.scrollTo(0, document.body.scrollHeight)

// 無限往上走
window.scrollTo(0, 0)

[php] 壓縮單檔

<?php
$files = array('jquery-1.6.min.js', 'social.js');
	$zip = new ZipArchive();
	$zip_name = time().".zip"; // Zip name
	$zip->open($zip_name,  ZipArchive::CREATE);
		foreach ($files as $file) {
			echo $path = "template_final/".$file;
			if(file_exists($path)){
			  $zip->addFromString(basename($path),  file_get_contents($path));  
			} else {
			   echo "file does not exist";
			}
		}
	$zip->close();
?>

[css] hide scrollBar

//方式一
#parent{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#child{
    width: 100%;
    height: 100%;
    overflow: auto;
    padding-right: 15px; /* Increase this value for cross-browser compatibility */
}

//方式二,Using Position: absolute
#parent{
    height: 100%;
    width: 100%;
    overflow: hidden;
    position: relative;
}

#child{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: -15px; /* Decrease this value for cross-browser compatibility */
    overflow: auto;
}

Array Api

Video Source : https://www.youtube.com/watch?v=sRUHJJugU9s&list=PLfMzBWSH11xa-iNnQG2555lgi4574nZOh&index=11

let str = 'Hooray for Arrays! Tips and Tricks for Javascript\'s Best Object!'
let arr = [1,2,3,4,56,76,8];

// Array is Array
var sheepIsArray = Array.isArray(['yan', 'tan', 'tethera', 'methera']);
var sheepForm = Array.from('Hooray for Arrays! Tips and Tricks for JavaScript\'s Best Object');

console.log({
  a: Array.from(str),
  b: Array.from(str, x => x + x), 
  c: Array.from(arr), 
  d: Array.from({length: 4}, (v, i) => i + i)
});

var anArray = new Array('a');       // ['a']
var thatArray = new Array(3);       // [null, null, null];
var arrayOf3 = Array.of(3);    // [3]; fix new Array(3)

var arr = [1,2,3,4,5];
delete arr[3]; // [1, 2, 3, empty × 1, 5] ===> [1, 2, 3, ,5];

var sheepShift = ['yan', 'tan', 'tethera', 'methera'].shift();
var sheepPop = ['yan', 'tan', 'tethera', 'methera'].pop();
var sheepUnshift = ['yan', 'tan', 'tethera', 'methera'].unshift('ipip');
var sheepPush = ['yan', 'tan', 'tethera', 'methera'].push('Sheng');

// br precise with splice
var sheepSplice = ['yan', 'tan', 'tethera', 'methera'].splice(1, 1);

// br precise with splice negative
var sheeepSpliceNegative = ['yan', 'tan', 'tethera', 'methera'].splice(-2, 1);

// splice adds, too
var sheepSpliceAdd = ['yan', 'tan', 'tethera', 'methera'].splice(1, 0, 'xoooxxx');

// push arrays together with concat
var sheepConcat = ['yan', 'tan', 'tethera', 'methera'].concat([1,2,3,4,24,1000]);

// toString will make an array into a string
var sheepString = ['yan', 'tan', 'tethera', 'methera'].toString();

// ToString get then same result with join();
var sheepJoin = ['yan', 'tan', 'tethera', 'methera'].join();

// you can change the join separator
var sheepJoinWithMask = ['yan', 'tan', 'tethera', 'methera'].join('+ ');

// extending arrays is easy with Array.copyWithin in ES6
// take two elements statring ar 0 and insert them at 2, will overwrite, not extend 
// copyWithin(target, start, end)
var sheepCopyWithIn = ['yan', 'tan', 'tethera', 'methera'].copyWithin(2, 0, 2);

// fill arrays quickly with Array.fill in ES6, overwrite all array elements value
var evilLaugh = new Array(25);
evilLaugh.fill('yo'); // ["yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo", "yo"]

// user find when you want to find the result of a function
// taleArray has a random selection of words from that A Tale of Two Cities quote
var sheepFind = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].find(item => {
  return item[0] === 'w'
});

// if we want the index of the matching item, use findIndex;
var sheepFindIndex = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].findIndex(item => {
    return item[0] === 'w'
})

// if we want to know whether one or more elements meets our test, we can use some();
var sheepSome = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].some(item => item[0] === 'w');

// if we need to be sure that "every" items passes our test, we can use every()
var sheepEvery = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].every(item => item[0] === 'w');

// use indexOf when you know what element you want 
var sheepIndexOf = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].indexOf('window');

// However: if you are trying to find NaN;
// indexOf won't find it
var NaNArray = [0, 1, 'm', NaN];
var findNaN = NaNArray.indexOf(NaN);

// findIndex will:
var findIndexNaN = NaNArray.findIndex(item => Number.isNaN(item));

// you can give an index to start at;
// indexOf [target, index_at]
var sheepIndexOf = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].indexOf('window', 3);

// lastIndexOf is like indexOf, but it searches from the end
var sheepLastIndexOf = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].lastIndexOf('tan');

// if you just want to know if your array includes an element,
// but you don't care where it is, use includes();
var sheepIncludes = ['yan', 'tan', 'tethera', 'window', 'wintheworld', 'methera'].includes('tan');

// watch out: sort according to string Unicode code points
var mixedUpArray = [2, 10, 'five', 'Six'];
var mixedNumberArray1 = [2, 10, 29, 3300, 399, -1, 0, -3, -100];
var mixedNumberArray2 = [2, 10, 29, 3300, 399, -1, 0, -3, -100];

var mixedUpArraySort = mixedUpArray.sort();
var mixedNumberArraySort1 = mixedNumberArray1.sort((a, b) => a - b );
var mixedNumberArraySort2 = mixedNumberArray2.sort((a, b) => b - a );

// the new Set object in ES6 makes easier to get arrays of unique elements
var wWords = ['was', 'was', 'what', 'with', 'windows', 'wish', 'windows'];
var uniqueWords = Array.from(new Set(wWords));

// reverse an array 
var wWords = ['was', 'was', 'what', 'with', 'windows', 'wish', 'windows'];
var reverseArray = wWords.reverse();

// reduce
var wWords = ['www', 'what', 'withes', 'windows', 'wish', 'windows'];
var reduceWords = wWords.reduce((acc, cur) => {
    return acc.length > cur.length ? acc : cur;
})

// for-in is weird
var wWords = [undefined, null, '', 'www', 'what', 'withes', 'windows', 'wish', 'windows'];
for (var word in wWords) {
    console.log(`wWords-index-${word}`, wWords[word]);
}

// forEach
var sparseArray = [1, '', 3, null, , undefined];
// forEach cant handle empty value
sparseArray.forEach(item => console.log(`item-forEach-${item}`));

// entries && let ~ of 
// entries return [key, value] in elements
var iterator = [1, '', 3, null, , undefined].entries();
for (let item of iterator) {
    console.log(`item-entries-${item}`);
}

// keys 
var keyIterator = [1, '', 3, null, , undefined].keys();
for (let item of keyIterator) {
    console.log(`item-keys-${item}`);
}

console.log('sheepIsArray', sheepIsArray);
console.log('sheepForm', sheepForm);
console.log('sheepShift', sheepShift);
console.log('sheepPop', sheepPop);
console.log('sheepUnshift', sheepUnshift);
console.log('sheepPush', sheepPush);
console.log('sheepSplice', sheepSplice);
console.log('sheeepSpliceNegative', sheeepSpliceNegative);
console.log('sheepSpliceAdd', sheepSpliceAdd);
console.log('sheepConcat', sheepConcat);
console.log('sheepString', sheepString);
console.log('sheepJoinWithMask', sheepJoinWithMask);
console.log('sheepCopyWithIn', sheepCopyWithIn);
console.log('sheepFind', sheepFind);
console.log('sheepFindIndex', sheepFindIndex);
console.log('sheepSome', sheepSome);
console.log('sheepIndexOf', sheepIndexOf);
console.log('findNaN', findNaN);
console.log('findIndexNaN', findIndexNaN);
console.log('sheepIndexOf', sheepIndexOf);
console.log('sheepLastIndexOf', sheepLastIndexOf);
console.log('sheepIncludes', sheepIncludes);
console.log('mixedUpArraySort', mixedUpArraySort);
console.log('mixedNumberArraySort1', mixedNumberArraySort1);
console.log('mixedNumberArraySort2', mixedNumberArraySort2);
console.log('uniqueWords', uniqueWords);
console.log('reverseArray', reverseArray);
console.log('reduceWords', reduceWords);

[css] Unit

name desc
px 絕對單位,頁面按精確像素展示
em 相對單位,基準點為父節點字體的大小,如果自身定義了 font-size 按自身來計算(瀏覽器默認字體是16px),整個頁面內1em不是一個固定的值。
rem 相對單位,可理解為」root em」, 相對根節點html的字體大小來計算,CSS3新加屬性,chrome/firefox/IE9+支持。
vw viewpoint width,視窗寬度,1vw等於視窗寬度的1%。
vh viewpoint height,視窗高度,1vh等於視窗高度的1%。
vmin vw和vh中較小的那個
vmax vw和vh中較大的那個
% 百分比
in
cm 厘米
mm 毫米
pt:point 大約1/72寸
pc pica,大約6pt,1/6寸
ex 取當前作用效果的字體的x的高度,在無法確定x高度的情況下以0.5em計算(IE11及以下均不支持,firefox/chrome/safari/opera/ios safari/android browser4.4+等均需屬性加麼有前綴)
ch 以節點所使用字體中的「0」字符為基準,找不到時為0.5em(ie10+,chrome31+,safair7.1+,opera26+,ios safari 7.1+,android browser4.4+支持)

JSON Api

JSON.stringify(obj, replacer, space)
接受一個JavaScript 對象並將其轉換為一個JSON 字符串。
replacer

const user = {
  id: 229,
  name: 'John',
  email: '[email protected]'
};
 
function replacer(key, value) {
  if (key === 'email') {
    return undefined;
  }
  return value;
}
 
const userStr = JSON.stringify(user, replacer);
// "{"id":229,"name":"John"}"

space

const user = {
  name: 'John',
  email: '[email protected]',
  plan: 'Pro'
};
 
const userStr = JSON.stringify(user, null, '...');
// "{
// ..."name": "John",
// ..."email": "[email protected]",
// ..."plan": "Pro"
// }"

在實際使用中,我們可能會格式化一些複雜的對象,這些對象往往對象內嵌套對象。直接看起來並不那麼直觀,結合上面的的replacer 和space 參數,我們可以這樣格式化複雜對象:

var censor = function(key,value){
    if(typeof(value) == 'function'){
         return Function.prototype.toString.call(value)
    }
    return value;
}
var foo = {bar:"1",baz:3,o:{name:'xiaoli',age:21,info:{sex:'男',getSex:function(){return 'sex';}}}};
console.log(JSON.stringify(foo,censor,4))

||

{
    "bar": "1",
    "baz": 3,
    "o": {
        "name": "xiaoli",
        "age": 21,
        "info": {
            "sex": "男",
            "getSex": "function (){return 'sex';}"
        }
    }
}

JSON.parse(string, function)

  1. 接受一個JSON 字符串並將其轉換成一個JavaScript 對象。
  2. 可以接受第二个参数,它可以在返回之前转换对象值。比如这例子中,将返回对象的属性值大写:
const user = {
  name: 'John',
  email: '[email protected]',
  plan: 'Pro'
};
 
const userStr = JSON.stringify(user);
 
const newUserStr = JSON.parse(userStr, (key, value) => {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value;
});
 
console.log(newUserStr); //{name: "JOHN", email: "[email protected]", plan: "PRO"} 

toJSON方法 :
如果一個被序列化的對象擁有toJSON 方法,那麼該toJSON 方法就會覆蓋該對象默認的序列化行為:不是那個對像被序列化,而是調用toJSON 方法後的返回值會被序列化

var obj = {
    foo: 'foo',
    toJSON:function(){
        return 'bar';
    }
}
JSON.stringify(obj);//'"bar"'
JSON.stringify({x:obj});//'{"x":"bar"}'

[scss] paragraph

// 計算段落用
@mixin paragraph($height,$many){
    height: $height * $many;
    line-height: $height;
    overflow: hidden;
}

[css] Input Css

input:placeholder-shown
input:required
input:optional
input:readonly
input:valid
input:invalid
input:checked

[html] Document Head

<!--meta标签-->
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="format-detection"content="telephone=no, email=no" />

<!--viewport-->
<!--视图窗口,移动端特属的标签。一般使用下面这段代码即可:-->
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, minimal-ui" />
<!--上面的代码依次表示设置宽度为设备的宽度,默认不缩放,不允许用户缩放(即禁止缩放)
,在网页加载时隐藏地址栏与导航栏(ios7.1新增)。-->

<!--width – // [pixel_value | device-width] viewport 的宽度,范围从 200 到 10,000,默认为 980 像素-->
<!--height – // [pixel_value | device-height ] viewport 的高度,范围从 223 到 10,000 -->
<!--initial-scale – // float_value,初始的缩放比例 (范围从 > 0 到 10)-->
<!--minimum-scale – // float_value,允许用户缩放到的最小比例-->
<!--maximum-scale – // float_value,允许用户缩放到的最大比例-->
<!--user-scalable – // [yes | no] 用户是否可以手动缩放-->
<!--target-densitydpi = [dpi_value | device-dpi | high-dpi | medium-dpi | low-dpi] 目标屏幕像素密度-->

<!--apple-mobile-web-app-capable-->
<!--是否启动webapp功能,会删除默认的苹果工具栏和菜单栏。-->
<meta name="apple-mobile-web-app-capable" content="yes" />

<!--apple-mobile-web-app-status-bar-style-->
<!--当启动webapp功能时,显示手机信号、时间、电池的顶部导航栏的颜色。
默认值为default(白色),可以定为black(黑色)和black-translucent(灰色半透明)。
这个主要是根据实际的页面设计的主体色为搭配来进行设置。-->
<meta name="apple-mobile-web-app-status-bar-style" content="black" />

<!--telephone & email-->
<!--忽略页面中的数字识别为电话号码-->
<meta name="format-detection" content="telphone=no, email=no" />

<!--其他meta-->
<!-- 启用360浏览器的极速模式(webkit) -->
<meta name="renderer" content="webkit">
<!-- 避免IE使用兼容模式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 针对手持设备优化,主要是针对一些老的不识别viewport的浏览器,比如黑莓 -->
<meta name="HandheldFriendly" content="true">
<!-- 微软的老式浏览器 -->
<meta name="MobileOptimized" content="320">
<!-- uc强制竖屏 -->
<meta name="screen-orientation" content="portrait">
<!-- QQ强制竖屏 -->
<meta name="x5-orientation" content="portrait">
<!-- UC强制全屏 -->
<meta name="full-screen" content="yes">
<!-- QQ强制全屏 -->
<meta name="x5-fullscreen" content="true">
<!-- UC应用模式 -->
<meta name="browsermode" content="application">
<!-- QQ应用模式 -->
<meta name="x5-page-mode" content="app">
<!-- windows phone 点击无高光 -->
<meta name="msapplication-tap-highlight" content="no">

<!--apple-touch-icon-->
<!--如果apple-mobile-web-app-capable设置为yes了,
那么在iPhone,iPad,iTouch的safari上可以使用添加到主屏按钮将网站添加到主屏幕上。
而通过设置相应apple-touch-icon标签,则添加到主屏上的图标就会使用我们指定的图片。
以下是针对ox不同设备,选择一个最优icon。
默认iphone的大小为60px,ipad为76px,retina屏乘以2倍。-->
<link rel="apple-touch-icon" href="touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">
<!--注:ios7不再为icon添加特效,ios7以前则默认为icon添加特效-->

<!--apple-touch-startup-image-->
<!--同样基于apple-mobile-web-app-capable设置为yes,-->
<!--可以用WebApp设置一个类似NativeApp的启动画面。-->
<link rel="apple-touch-startup-image" href="/startup.png">
<!--和apple-touch-icon不同,apple-mobile-web-app-capable不支持sizes属性,-->
<!--所以使用media来控制retina和横竖屏加载不同的启动画面。-->

<!--// iPhone-->
<link href="apple-touch-startup-image-320x460.png" media="(device-width: 320px)" rel="apple-touch-startup-image" />
<!--// iPhone Retina-->
<link href="apple-touch-startup-image-640x920.png" media="(device-width: 320px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />
<!--// iPhone 5-->
<link rel="apple-touch-startup-image" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" href="apple-touch-startup-image-640x1096.png">
<!--// iPad portrait-->
<link href="apple-touch-startup-image-768x1004.png" media="(device-width: 768px) and (orientation: portrait)" rel="apple-touch-startup-image" />
<!--// iPad landscape-->
<link href="apple-touch-startup-image-748x1024.png" media="(device-width: 768px) and (orientation: landscape)" rel="apple-touch-startup-image" />
<!--// iPad Retina portrait-->
<link href="apple-touch-startup-image-1536x2008.png" media="(device-width: 1536px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image" />
<!--// iPad Retina landscape-->
<link href="apple-touch-startup-image-1496x2048.png"media="(device-width: 1536px)  and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)"rel="apple-touch-startup-image" />

[小程式] X光機

html,
body {
  height: 100%;
  margin: 0;
}

body {
  font-family: Monaco;
  font-size: 12px;
  color: rgba(0,0,0,.7);
}

svg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: block;
  width: 100%;
  height: 100%;
}

div,
a {
  position: relative;
  padding: 1em;
}

div {
  text-shadow: 0 1px 0 rgba(255,255,255,.5);
}

span {
  color: rgba(0,0,0,.4);
}

a {
  color: rgba(255,0,0,.5);
}

[scss] ellipsis

// 多餘文字變成....
%omitted-words {
  overflow : hidden;
  text-overflow : ellipsis;
  white-space : nowrap;
}

@mixin omitted-words {
  @extend %omitted-words;
}

[js] webvoice

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <title>Voice Demo</title>
    </head>
    
    <body>
        <div id="show"></div>
        <script>
            var show = document.getElementById('show');
            var recognition = new webkitSpeechRecognition();
            recognition.continuous=true;
            recognition.interimResults=true;
            // recognition.lang="cmn-Hant-TW";
            recognition.lang="en-US";
            recognition.onstart=function(){
              console.log('開始辨識...');
            };
            recognition.onend=function(){
              console.log('停止辨識!');
            };
            recognition.onresult=function(event){
              var i = event.resultIndex;
              var j = event.results[i].length-1;
              show.innerHTML = event.results[i][j].transcript;
            };
            recognition.start();
        </script> 
    </body>
</html>

[vue] [sliderShow]

<template>
  <!-- @wheel="onWheel"-->
  <div class="slider"
    @mouseover="clearTimerEvent"
    @mouseleave="addTimerEvent"
    @touchstart="onTouchStart"
    @mousedown="onTouchStart">
    <div class="slider_list" :style="setStyle" @transitionend="onTransitionEnd">
      <div class="slider_item" v-for="(arr, index) in cloneSliderArr" :key="index" :style="{ backgroundImage: `url(${arr.img})` }"></div>
    </div>

    <div class="slider_pagination">
      <div class="slider_pagination_bullet" :class="{active: index + 1 === computeIndex}" 
      v-for="(arr, index) in bullets" :key="index"
      @click="goTo(index + 1)"></div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'slider',
    props: {
      seconds: {
        type: Number,
        default: 3000,
      },
      speed: {
        type: Number,
        default: 500,
      },
    },
    data() {
      return {
        sliderArr: [{
          img: 'https://images.unsplash.com/photo-1494005199821-2cb74a8e75fb?auto=format&fit=crop&w=1950&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
        },
        {
          img: 'https://images.unsplash.com/photo-1495206255513-257bdf652e26?auto=format&fit=crop&w=2090&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
        },
        {
          img: 'https://images.unsplash.com/photo-1507706132643-4b3dabbca8b3?auto=format&fit=crop&w=2134&q=60&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
        }],
        
        isLoop: true,          // 增加前後 
        startTime: null,
        clientWidth: 0,
        currentPage: 1,
        translateX: 0,
        startPos: null,
        startTranslate: 0,
        transitionDuration: 0,
        delta: 0,

        timer: null,
      };
    },
    watch: {},
    mounted() {
      this.slideInit();
    },
    computed: {
      computeIndex() {
        let index = 0;
        
        console.log('this.currentPage: ', this.currentPage);
        if (this.currentPage === 1 || this.currentPage === this.slides.length - 1) {
          index = 1;
        } else if (this.currentPage === this.slides.length - 2 || this.currentPage === 0) {
          index = this.slides.length - 2;
        } else {
          index = this.currentPage;
        }

        return index;
      },
      bullets() {
        let computeBullets = 0;

        if (this.isLoop) {
          computeBullets = this.sliderArr.length - 2;
        } else {
          computeBullets = this.sliderArr.length;
        }

        return computeBullets;
      },
      cloneSliderArr() {
        const sliderArrFirst = this.sliderArr[0];
        const sliderArrLast = this.sliderArr[this.sliderArr.length - 1];

        this.sliderArr.push(sliderArrFirst);
        this.sliderArr.unshift(sliderArrLast);

        return this.sliderArr;
      },
      setStyle() {
        return {
          transform: `translate3d(${this.translateX}px, 0px, 0px)`,
          transitionDuration: `${this.transitionDuration}ms`,
        };
      },
    },
    methods: {
      slideInit() {
        this.$nextTick(() => {
          this.getSlideList();
          this.getClientWidth();
          this.move(this.currentPage);
        });
      },

      getSlideList() {
        this.slides = this.$el.querySelectorAll('.slider .slider_item');
        this.setTimer();
      },
      getClientWidth() {
        this.clientWidth = this.slides ? this.slides[0].clientWidth : null;
      },

      clearTimerEvent() {
        this.removeTimer();
      },
      addTimerEvent() {
        this.setTimer();
      },

      setTimer() {
        this.timer = setInterval(this.setTimerNext, this.seconds);
      },
      removeTimer() {
        clearInterval(this.timer);
      },

      setTimerNext() {
        this.transitionDuration = 500;
        this.currentPage = this.currentPage + 1;
        this.move(this.currentPage);
      },

      onTransitionEnd() {
        if (this.timer) {
          if (this.currentPage === this.slides.length - 1) {
            this.transitionDuration = 0;
            this.currentPage = 1;
            this.move(this.currentPage);
          }
        }
      },

      next() {
        if (this.currentPage < this.slides.length - 1) this.currentPage = this.currentPage + 1;
        this.move(this.currentPage);
      },
      prev() {
        if (this.currentPage > 0) this.currentPage = this.currentPage - 1;
        this.move(this.currentPage);
      },
      goTo(index) {
        this.currentPage = index;
        this.move(index);
      },
      move(index) {
        this.translateX = -(index * this.clientWidth);
        this.startTranslate = this.translateX;
      },

      setTranslate(value) {
        this.translateX = value;
      },
      getTranslate() {
        return this.translateX;
      },

      getTouchPos(e) {
        const key = 'pageX';
        return e.changedTouches ? e.changedTouches[0][key] : e[key];
      },
      onTouchStart(e) {
        if (this.timer) {
          this.removeTimer();
        }

        this.startPos = this.getTouchPos(e);
        this.startTime = new Date().getTime();
        this.transitionDuration = 0;

        // 4
        if (this.currentPage === this.slides.length - 1) {
          this.currentPage = 1;
          this.startTranslate = -(this.currentPage * this.clientWidth);
        // 0
        } else if (this.currentPage === 0) {
          this.currentPage = this.slides.length - 2;
          this.startTranslate = -(this.currentPage * this.clientWidth);
        }

        document.addEventListener('touchmove', this.onTouchMove, false);
        document.addEventListener('touchend', this.onTouchEnd, false);
        document.addEventListener('mousemove', this.onTouchMove, false);
        document.addEventListener('mouseup', this.onTouchEnd, false);
      },
      onTouchMove(e) {
        this.delta = this.getTouchPos(e) - this.startPos;

        this.setTranslate(this.startTranslate + this.delta);
      },

      onTouchEnd() {
        if (!this.timer) {
          this.setTimer();
        }

        const isQuickAction = new Date().getTime() - this.startTime < 1000;

        this.transitionDuration = this.speed;

        if (this.delta < -100 || (isQuickAction && this.delta < -15)) {
          this.next();
        } else if (this.delta > 100 || (isQuickAction && this.delta > 15)) {
          this.prev();
        }

        document.removeEventListener('touchmove', this.onTouchMove);
        document.removeEventListener('touchend', this.onTouchEnd);
        document.removeEventListener('mousemove', this.onTouchMove);
        document.removeEventListener('mouseup', this.onTouchEnd);
      },
      onWheel(e) {
        if (e.deltaY > 0) {
          this.next();
        } else {
          this.prev();
        }
      },
    },
  };
</script>

<style lang="scss">
.slider {
  margin-top: 100px;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.slider .slider_list {
  display: flex;
  width: 100%;
  height: 200px;
  transition: all 0ms ease;
}

.slider .slider_list .slider_item {
  width: 100%;
  height: 100%;
  background: #333;
  background-size: cover;
  background-origin: center;

  display: flex;
  flex-shrink: 0;

  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 48px;
  color: #fff;
}

.slider .slider_pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.slider .slider_pagination .slider_pagination_bullet {
  margin: 0 3px;
  width: 10px;
  height: 10px;
  border: 1px solid #dddddd;
  background: #dddddd;
  border-radius: 100%;
  &.active {
    background: #ffffff;
  }
}
</style>

[js] setSelectionRange api

<textarea id="textarea" name="textarea" rows="10" cols="30">
  Happy kittens dancing
</textarea>
<button id="click">Click</button>
document.querySelector('#click').addEventListener('click', () => {
  setCursor(
    document.getElementById('textarea'),
    0,
    13
  )
}, false);

function setCursor(el, st, end) {
  if (el.setSelectionRange) {
    el.focus();
    el.setSelectionRange(st, end);
  } else {
    // IE
    if (el.createTextRange) {
      range = el.createTextRange();
      range.collapse(true);
      range.moveEnd('character', end);
      range.moveStart('character', st);
      range.select();
    }
  }
}

[js] array.find

if(s.traits.find(trait => !trait.checked)){
  s.traits.forEach(trait => trait.checked = true) 
} else {
  s.traits.forEach(trait => trait.checked = false)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.