Git Product home page Git Product logo

training's Introduction

my-notes

我的一些笔记&demo

training's People

Contributors

silif avatar

Watchers

James Cloos avatar  avatar

training's Issues

css技巧

弹窗后禁止滚动

css

html{
    overflow: hidden;
}

js

$(document.body).css('border-right',widthScrollbar + 'px solid transparent');

理解flex布局中的剩余空间计算方式

理解flex布局中的剩余空间计算方式

父元素设置display:flex后,它就成为了一个flex容器,然后就可以运用CSS flexbox布局提供的属性进行布局了。

父元素可选值

属性 意义
flex-direction row/row-reverse/column/column-reverse 主轴弹性方向
flex-wrap nowrap/wrap/wrap-reverse 换行行为
justify-content flex-start/flex-end/center/space-between/space-around/space-evenly/start/end/left/right 在主轴上的对齐方式
align-items flex-start/flex-end/center/baseline /stretch 交叉轴上对齐方式
align-content flex-start/flex-end/center/space-between/space-around/stretch 多根轴线的对齐方式

子元素的可选值

属性 意义
order <int> 排列顺序,默认为0,越小越靠前
flex-basis <number像素>/auto 分配多余空间之前,项目占据的主轴空间,默认auto
flex-grow <number> 元素放大比例,默认为0
flex-shrink <number> 元素缩小比例,默认为1
flex <flex-grow> <flex-shrink> <flex-basis> flex-grow/flex-shrink/flex-basis的缩写方式
align-self auto/flex-start/flex-end/center/baseline/stretch 允许该元素与其他元素用不一样的对齐方式

flex属性如何计算布局

子元素中我们用的最多可能就是子元素的flex简写形式:

flex: <flex-grow> <flex-shrink> <flex-basis>

浏览器是怎么通过这三个属性分配空间的呢?

首先先分析各个子元素的flex-basis值,若果是npx的宽度,则先给他们计算成npx宽度再执行下一步的计算;如果默认值是auto,则计算成该元素本身的大小再执行下一步的计算。

如果子元素的宽度之和大于父元素的可用空间,此时剩余空间小于0像素,放大比例flex-grow属性不会生效;再根据flex-shrink值来计算各自的缩小比例,如果其中一个子元素的flex-shrink值是0,则该元素不会缩小,其他非0值元素各自按比例缩小;如果所有子元素的flex-shrink值都为0,则所有子元素都不会缩小,并溢出到父元素外面。

如果子元素的宽度之和小于父元素的可用空间,此时剩余空间大于0像素,缩小比例flex-shrink属性不会生效,则根据flex-grow值来计算各自的放大比例;当其中一个子元素flex-grow值为0时,该元素不会放大,其他元素根据各自的flex-grow进行比例放大;若所有子元素的flex-grow值都为0,则所有子元素都不会放大。

isset, post, get,cookie,session

isset — 检测变量是否设置

e.g 💯

<form action = "<?php $_PHP_SELF ?>" method = "POST">
    Name: <input type = "text" name = "name" />
    <input type = "submit" />
</form>
<?php
if (isset($_POST["name"])) {
      echo $_POST["name"];
}else{
      echo "NO valid name"; 
}

GET && POST

get

  • get会在浏览器显示参数,并且限制在1024characters之内
  • 敏感信息(password)不要使用get来传送至服务器
  • get不能用来传送binary data,比如images,word documents
  • The data sent by GET method can be accessed using QUERY_STRING environment variable
  • PHP 提供 $_GET["参数"] 来获取发送的参数

post

  • 发送的数据没有大小限制
  • send ASCII as well as binary data
  • The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.
  • PHP 提供 $_POST["参数"] 来获取发送的参数

cookie操作

设置cookie

方法:setcookie(name, value, expire, path, domain, security);

  • path 指定cookie有效目录
  • security 设置为1,时,只允许https携带;设置为0时,可以用http携带
    e.g:
setcookie("name", "John Watkin", time()+3600, "/","", 0);

获取cookie

方法:$_COOKIE["name"] 或者$HTTP_COOKIE_VARS["name"]
e.g :

<?php
     if( isset($_COOKIE["name"]))
        echo "Welcome " . $_COOKIE["name"] . "<br />";
     else
        echo "Sorry... Not recognized" . "<br />";
  ?>

删除cookie

调用setcookie来删除cookie

setcookie( "name", "", time()- 60, "/","", 0);

session

初步了解

  • PHPSESSIONID在调用函数session_start()后向客户端发送32位唯一标识,在调用session_destroy()后被销毁
  • 服务器端会在特定的路径下的文件里创建一个文件来存储唯一标识,路径由php.ini文件配置
  • session依赖cookie,cookie被禁止时session也不乏使用,不过可以在 url 中传递 session_id
  • 同步登陆时,即使设置了cookie,也应该依据session来判断是否为登陆状态,安全性高

更多参考

session原理总结
php手册session函数
login-with-session
using-sessions-session-variables-in-a-php-login-script

promisify

error first callback

执行一个回调函数时,将错误信息当成该回调函数的第一个参数、将正常数据当成其他参数的写法,比如node.js里 fs.readFile的回调函数

fs.readFile(path, (error, data) => {
  if (error) {
  } else {
    console.log(data);
  }
});

promise

异步操作时,相对于回调函数,使用promise或者async/await能让代码可读性变高,也能避免地狱回调,怎么把error first callback 转换成promise模式呢?我们借助promisify来实现这种功能。

promisify

该函数接受一个函数作为参数,返回加工后的函数B;B的参数为调用promisify后生成的函数的参数(废话),下面args即为上方fs.readFile 函数的path参数。

function promisify(func) {
  return function (...args) {
    return new Promise((resolve, reject) => {
      func(...args, (error, data) => {
        if (error) {
          reject(error);
        } else {
          resolve(data);
        }
      });
    });
  };
}

结论

简单实现了promisify函数,将回调转换成promise
仍需注意this的指向这种问题。

css技巧(背景与边框)

透明边框

html如下:

<style>
.centerall{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .wrap{
    background: url(img/1.jpg);
    height: 300px;
    width: 500px;
  }
  .content{
    border: 40px solid rgba(0,0,0,.6);
    height: 100px;
    width: 300px;
     /*  height: 100%;
    width: 100%;*/
    box-sizing: border-box;
    background: #fff;
    margin: auto;
    background-clip: padding-box;
  }
</style>
<div class="wrap centerall">
  <div class="content centerall">你好</div>
</div>

截图如下:
screenshot 1
其实分成三个dom层也能实现同样的效果。

多边框

box-shaow,outline实现

html如下:

<style type="text/css">
    .box-shadow{
      margin: 100px;
      height: 200px;
      width: 300px;
      /*background: yellow;
      box-shadow: 0 0 0 10px #333;*/
      /*第一个参数x轴,第二个参数y轴,第三个参数阴影浓度,第四个参数阴影宽度,将参数浓度设置为0可模拟边框,并且多个边框可以层层叠加哦*/
      background: yellowgreen;
      box-shadow: 0 0 0 10px #222, 0 0 0 15px deeppink,0 0 0 35px blue;;
    }
    .outline {
      height: 100px;
      background: grey;
      /*border: 10px solid #655;*/
      border: 2px dashed #000;
      outline: 8px solid grey;
    }
  </style>
  <div class="box-shadow"></div>
  <div class="outline"></div>

截图如下:
screenshot 1

javascript

从cookie中取出某个值

function getCookieByName(name) {
    var search = name + "="
    var returnvalue = "";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search)
        // if cookie exists
        if (offset != -1) {
            offset += search.length
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            returnvalue = unescape(document.cookie.substring(offset, end))
        }
    }
    return returnvalue;
}

img 转base64(img传到server的时候可以这样传)

function toDataUrl(src, callback, outputFormat) {
  var img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var dataURL;
    canvas.height = this.height;
    canvas.width = this.width;
    ctx.drawImage(this, 0, 0);
    dataURL = canvas.toDataURL(outputFormat);
    callback(dataURL);
  };
  img.src = src;
}

var src = document.getElementById('img').src;
toDataUrl(src, function(base64Img) {
  console.log(base64Img);
});

在本地跑的时候会报错,放在server上就不会了,或者使用Chrome Dev Editor

input[type="file"]上传图片时转base64再传

$('input[type=file]').change(function(){
    var file = this.files[0];
    console.log(file);
    var reader=new FileReader();
    reader.onload = function(e){
        var dataURL = reader.result;
    }
    console.log(reader.readAsDataURL(file));
})

repeat String函数的实现

String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';
   for (var i = 0; i < times; i++) {
      str += this;
   }
   return str;
};

以前没用过这个this

iframe 中父页面操作子页面dom

$("iframe").contents().find("#chequeOut").hide(); // 或者
window.frames["PIframe"].$('#oprating').hide();

scroll 事件优化

function doSomething() {
    //doSomething; 
}
var waiting = false;
$(window).scroll(function() {
    if (waiting) {
        return;
    }
    waiting = true;
    doSomething();
    setTimeout(function() {
        waiting = false;
    }, 500)
})

更多:develop-high-performance-onscroll-event

原型与原型链

jsobj

使用网格的一点建议

pure.css的网格

.pure-g {
    letter-spacing: -0.31em; /* Webkit: collapse white-space between units */
    *letter-spacing: normal; /* reset IE < 8 */
    *word-spacing: -0.43em; /* IE < 8: collapse white-space between units */
    text-rendering: optimizespeed; /* Webkit: fixes text-rendering: optimizeLegibility */

    /*
    Sets the font stack to fonts known to work properly with the above letter
    and word spacings. See: https://github.com/yui/pure/issues/41/

    The following font stack makes Pure Grids work on all known environments.

    * FreeSans: Ships with many Linux distros, including Ubuntu

    * Arimo: Ships with Chrome OS. Arimo has to be defined before Helvetica and
      Arial to get picked up by the browser, even though neither is available
      in Chrome OS.

    * Droid Sans: Ships with all versions of Android.

    * Helvetica, Arial, sans-serif: Common font stack on OS X and Windows.
    */
    font-family: FreeSans, Arimo, "Droid Sans", Helvetica, Arial, sans-serif;

    /*
    Use flexbox when possible to avoid `letter-spacing` side-effects.

    NOTE: Firefox (as of 25) does not currently support flex-wrap, so the
    `-moz-` prefix version is omitted.
    */

    display: -webkit-flex;
    -webkit-flex-flow: row wrap;

    /* IE10 uses display: flexbox */
    display: -ms-flexbox;
    -ms-flex-flow: row wrap;
}

/* Opera as of 12 on Windows needs word-spacing.
   The ".opera-only" selector is used to prevent actual prefocus styling
   and is not required in markup.
*/
.opera-only :-o-prefocus,
.pure-g {
    word-spacing: -0.43em;
}
.pure-u-1-3,.pure-u-2-3{
    display: inline-block;
    *display: inline;
    zoom: 1;
    letter-spacing: normal;
    word-spacing: normal;
    vertical-align: top;
    text-rendering: auto;
}
.pure-u-1-3 {
    width: 33.3333%;
    *width: 33.3023%;
}
.pure-u-2-3 {
    width: 66.6667%;
    *width: 66.6357%;
}
html {
  box-sizing: border-box;
}

*,
*:before,
*:after {
  box-sizing: inherit;
}

一些javascript写的数据结构算法题

统计一个字符串出现最多的字母

var findMaxLenChar = function (str) {
    var hash = {};
    for(var i = 0,len = str.length;i < len;i++) {
        var item = str.charAt(i);
        if(!(hash.item < len&&hash.item >= 0)) {
            hash.item += 1;
        }else {
            hash.item = 0;
        }
    }
  //  return hash;
  //  然后遍历forEach遍历hash,返回最大value的key
}

或者

arr.split('').reduce((p, k) => (p[k]++ || (p[k] = 1), p), {});
//  这里同样可以得到一个hash

数组去重

// es6
function uniq(arr) {
    return Array.from(new Set(arr))
}

获得一串随机字符串

function getRandomStr(n){
    var str = "qwertyuiopasdfghjklzxcvbnm1234567890";
    var len = str.length;
    var re = "";
    for(var i = 0;i < n;i++) {
        re += str.charAt(Math.floor(Math.random() * len))
    }
    return re;
}
getRandomStr(5)

flatten

[].concat.apply([], [[1],[2,3],[4]]) //  [ 1, 2, 3, 4 ]
// 这种方法还有点问题,下面的这个数组就没有用了。
var list1 = [[0, 1], [2, 3], [4, 5]];
const flatten = arr => arr.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
flatten(list1);
JSON.parse('[' + [[9, [2, 3, [4, 10, [6, 3]]], 6, 9], 1, 2, 3, 2, 3] + ']'); // [9, 2, 3, 4, 10, 6, 3, 6, 9, 1, 2, 3, 2, 3]
//  [[9, [2, 3, [4, 10, [6, 3]]], 6, 9], 1, 2, 3, 2, 3].toString() 还可以得到 "9,2,3,4,10,6,3,6,9,1,2,3,2,3" 这样的字符串。

判断一串字符是不是回文

function huiWen(str) {
  return str == str.split(' ').reverse().join(' ');
}

判断是否是整数

function isInterger(num){
  return num === parseInt(num,10)
}

ES6中用 Number.isInteger() 来判断

将函数参数转为数组

function add() {
    var args = [].slice.call(arguments); //ES5
    let args = Array.from(arguments); // ES6
    // 后续操作 ...
}
let add = (...args) => args.reduce((a,b) => a+b)  // ES6

实现一个Redux

套路

// 定一个 reducer
function reducer (state, action) {
  /* 初始化 state 和 switch case */
}

// 生成 store
const store = createStore(reducer)

// 监听数据变化重新渲染页面
store.subscribe(() => renderApp(store.getState()))

// 首次渲染页面
renderApp(store.getState()) 

// 后面可以随意 dispatch 了,页面自动更新
store.dispatch(...)

在此之前先定义 createStore() 函数

function createStore (reducer) {
    let state = null
    const listeners = []
    const subscribe = (listener) => listeners.push(listener)
    const getState = () => state
    const dispatch = (action) => {
        state = reducer(state, action)
        listeners.forEach((listener) => listener())
    }
    dispatch({}) // 初始化 state
    return { getState, dispatch, subscribe }
}

完整的例子

function createStore (reducer) {
    let state = null
    const listeners = []
    const subscribe = (listener) => listeners.push(listener)
    const getState = () => state
    const dispatch = (action) => {
        state = reducer(state, action)
        listeners.forEach((listener) => listener())
    }
    dispatch({}) // 初始化 state
    return { getState, dispatch, subscribe }
}

function themeReducer (state, action) {
    if (!state) return {
        themeName: 'Red Theme',
        themeColor: 'red'
    }
    switch (action.type) {
        case 'UPATE_THEME_NAME':
            return { ...state, themeName: action.themeName }
        case 'UPATE_THEME_COLOR':
            return { ...state, themeColor: action.themeColor }
        default:
            return state
    }
}
function renderApp(s){
    const titleDOM = document.getElementById('title')
    console.log(titleDOM)
    titleDOM.style.backgroundColor = s.themeColor
    titleDOM.innerHTML = s.themeName
}

const store = createStore(themeReducer)

store.subscribe(() => renderApp(store.getState()))

renderApp(store.getState())
store.dispatch({ type: 'UPATE_THEME_COLOR', themeColor: 'blue' })

参考教程动手实现 Redux

几个正则表达式的例子

向前查找

  • 把数字前一个字母变大写
"asd23asd23".replace(/\w(?=\d)/g,function(value){
     return  value.toUpperCase(); // asD23asD23
})
  • 把1或2前一个a替换成#
"a1d3f23a22".replace(/a(?=[12])/g,"#") // #1d3f23#22
  • 匹配所有a,但不包括d前面的a
"ad2asaa".replace(/a(?!d)/g,"A") //ad2AsAA
  • 格式化数字,如 12312312 => 12,312,312
'12312312'.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,'); // 12,312,312

我的其他正则例子

https://segmentfault.com/n/1330000005103527

筛选数字,带最多两位小数

/^\d+(\.\d{1,2})?$/.test(stringS);

二维数组的顺序组合

不确定元素个数的二维数组,需要把每个子数组按出现在父数组的位置进行串联排列。比如:
[['a','b','c'],[1,2]]
转换成
["a1", "a2", "b1", "b2", "c1", "c2"]

let a = ["A", "B"],
  b = [1, 2, 3],
  c = ["大", "小", "中"],
  d = ["👋", "😄", "👌"];
let arr = [a, b, c, d];

function arrsValues(arr) {
  let result = [];
  let countInOne = 1,
    count = 1,
    index = 0;
  while (index < arr.length) {
    countInOne = countInOne * arr[index].length;
    index++;
  }
  count = countInOne;
  for (let i = 0; i < arr.length; i++) {
    const curGroup = arr[i];
    countInOne = countInOne / curGroup.length;
    for (let j = 0; j < count; j++) {
      let pos = Math.floor(j / countInOne) % curGroup.length;
      result[j] = (result[j] || "") + curGroup[pos];
    }
  }
  return result;
}
console.log(arrsValues(arr));
//  ["A1大👋", "A1大😄", "A1大👌", "A1小👋", ...]

leetcode

Two Sum

link

example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

write by javascript

  • o( n^2 )
var twoSum = function(nums, target) {
    var out = [];
    for(let i = 0;i<nums.length;i++){
        for(let j = i+1;j<nums.length;j++){
            if(nums[i] + nums[j] == target){
                out.push(i);
                out.push(j);
                break;
            }
        }
    }
    return out;
};
  • better way(o(n))
var twoSum = function(nums, target) {
    var out = [];
    for(let i = 0; i< nums.length; i++){
        var secendIndex = nums.indexOf(target - nums[i])
        if(secendIndex > i ){
            out.push(i-1);
            out.push(secendIndex-1);
            break;
        }
    }
    return out;
};

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.