Code Monkey home page Code Monkey logo

blog's People

Contributors

tiu5 avatar

Watchers

 avatar

blog's Issues

FreeCodeCamp 算法题

Flexbox 布局

Flexbox 最适合是沿单个轴分布元素,要么是水平方向的,要么是垂直方向的。
Grid 它是二维的,也就是说水平和垂直方向都可以排列元素。

  • 一维布局,布局根据内容元素自适应:Flexbox
  • 二维布局,复杂非线性页面布局:Grid

拥抱自适应性

与浮动和其他传统布局不同的是,Flexbox 和 Grid 布局的出现是为了解决多设备出现的问题。

父元素和子元素

定义一个父容器:

.container{
    display: flex; /* 或者 display: inline-flex; */
}

容器里的子元素:

.item{
    order: {Int}; /* 设置排列顺序的权值 */
}

父容器的属性

flex-direction
  • row(默认值): 行排列,从左到右。
  • row-reverse: 反向,从右到左。
  • column: 列排列,从上到下。
  • column-reverse: 从下到上。
flex-wrap

一行或列不够放,多出的那一行/列要怎么放,用它 flex-wrap

  • nowrap(默认值): 单行显示。
  • wrap: 多行显示。
  • wrap-reverse: 多行显示。
flex-flow: flex-direction, flex-wrap

flex-flow: flex-direction + flex-wrap 的简写版。

justify-content 主轴上的伸缩项目对齐方式
  • flex-start: 靠起始位置
  • flex-end: 靠结束位置
  • center: 居中
  • space-between: 两头的项目贴边,其余间距一样
  • space-around: 所有项目间距都一样
align-items 侧轴上的伸缩项目(包括隐式)对齐方式
  • flex-start: 靠起始位置
  • flex-end: 靠结束位置
  • center: 居中
  • stretch
  • baseline
align-content 侧轴上的伸缩项目对齐方式
  • flex-start: 靠起始位置
  • flex-end: 靠结束位置
  • center: 居中
  • space-between: 两头的项目贴边,其余间距一样
  • space-around: 所有项目间距都一样
  • stretch
order: 设置排列的权值

order: {Int} 权值越小,排越前,可为负数。

flex-grow: 设置比例的单位

flex-grow: {+Int} 为负数时失效。父容器大小减去确定大小的项目,在去按比例分给该元素。

假设:父容器宽度为 1000px,里面有四个子项目(A, B, C, D),A, B 宽度为 100px,C 宽度为 20%,在 D 中 flex-grow: 2; 那么 D 的宽度为:(1000 - 100 - 100 - 1000 * 20) / 2 * 2 = 600 px

代码示例

flex-shrink: 定义 Flex 项目缩小比例
flex-basis: 设置主轴方向的大小,可看成是宽度/高度,不过权值比它们高
flex: flex-grow, flex-shrink, flex-basis

flex: none; => flex-grow: 0;flex-shrink: 0;flex-basis: auto;

align-self: 设置单独的 Flex 项目样式
  • flex-start: 靠起始位置
  • flex-end: 靠结束位置
  • center: 居中
  • stretch
  • baseline

PS: 跟 Grid 布局一起食用更佳。因为它俩很多属性都类似。

参考资料

Grid 布局

Grid 布局是什么?

它是一个二维的网格布局。

两个核心部分:父元素和子元素

二维有:行 (row)、列 (column)

我只是写了简单的笔记,没有实例截图,推荐大家看参考资料里的原文博客:带你入门 CSS Grid 布局

学习CSS Grid

首先我们要设置个网格容器

使用 display: grid 或者 display: inline-grid ,然后网格布局要有子元素,然后默认子元素是按行排列的。

设置显示网格

使用 grid-template-columnsgrid-template-rows 可以显式的设置网格布局的列和行。

/* 设置了两列,宽度分别为 20px 30px */
grid-template-columns: 20px 30px;

/* 设置了两行,高度分别为 20px 30px */
grid-template-rows: 20px 30px;

也可以使用其他单位,比如 百分比,rem 等。

另外有一个弹性单位:fr,这个按等分分的,比如:

grid-template-rows: 1fr 1fr 2fr;

上面代码中 1fr 表示的为布局可用空间大小的 1/4 ,因为上面 1 + 1 + 2 = 4。

当遇到多种长度单位时,fr 的计算这样的:

grid-template-rows: 20% 20px 1fr 3fr;
/* 这时候的 1fr = 网格大小 - 网格自身的20% - 20px 然后再除以 4 等分  */
设置最小和最大尺寸

使用 minmax() 接受两参数:最小值和最大值。

/* 高度根据元素大小变化但最大为 200px,最小宽度为 200px,最大为网格大小(父元素)的 50% */
grid-template-rows: minmax(auto, 200px);
grid-template-columns: minmax(200px, 50%);
设置多个相同尺寸的元素

使用 repeat() ,接受两参数:元素的个数,具体的尺寸大小。

/* 三列大小都为 200px,三行大小都为 200px */
grid-template-columns: repeat(3, 200px);
grid-template-columns: repeat(3, 200px);
/* 也可以这样写 */
grid-template-columns: 20px 30px repeat(2, 1fr) 40px;
网格间的间距
  • grid-row-gap:行与行间的间距
  • grid-column-gap:列与列间的间距
  • grid-gap:上面的缩写版,第一个参数为 grid-row-gap 的值,第二个参数为 grid-column-gap 的值,若只有一个值则两者都用同一个值。
grid-column-gap: 1px; /* 列的网格线间的间距 1px */
grid-row-gap: 1px; /* 行的网格线间的间距 1px */

/* 可以简写为:*/
grid-gap: 1px;
通过网格线坐标来定位 网格项目(grid items)

网格线怎么理解?我们拿汉字 来举例(因为我不想画图)。我们把这个看成是一个两行两列的布局,那么从左边数起,是不是有三个竖线,那么它们分别为 1,2,3。同样的从上往下数也有:1,2,3。

PS:感觉你也可以看出是 x,y 坐标图,只是原点是 (1, 1) 而不是 (0, 0),注意:这个是写在子元素的样式。、

  • grid-row-start:起始位置,接受参数为 网格线位置
  • grid-row-end:结束位置,接受参数为 网格线位置(可省略)
  • grid-column-start
  • grid-column-end
  • grid-row:起始和结束位置的简写,如果一个值时则只是设置起始位置
  • grid-column:如果有两个值时,则要用 / 隔开
  • grid-area:grid-row-start, grid-column-start, grid-row-end, grid-column-end
  • span 关键字后跟着一个数字,等于设置结束位置 = 起始位置加该数字行或列数
.item-1{
  grid-row-start: 2;
  grid-row-end: 3;
  /* 上面可以省略 grid-row-end */
  grid-row-start: 2;

  /* 同样的 grid-column-end 也一样 */
  grid-column-start: 2;
  grid-column-end: 3;
  /* 上面可以省略 grid-column-end */
  grid-column-start: 2;

  /* 也可以这样写 */
  grid-row: 2;
  grid-column: 2 / 3;
  grid-column: 2 / span 1;

  grid-area: 2 / 2;
  grid-area: 2 / 2 / 3;
}
网格线命名和使用

在父元素在定义网格时,用 [网格线名] 去定义。

.warp{
  display: grid;
  grid-template-rows: [row-1-s] 1fr [row-2-s] 1fr [row-2-e];
}
.item-1{
  grid-row: row-1-s / row-2-e;
}
repeat() 也可以命名网格线
.warp{
  display: grid;
  grid-template-rows: repeat(2, [row-s] 1fr [row-e]);
  grid-template-columns: repeat(2, [column-s] 1fr [column-e]);
}

这样的话,除了最外的框框那个网格线是一个命名,其他的网格线都有两个命名。然后它会自动加数字,避免命名冲突。以 字为例:

  |--------row-s---------|
    column-s |     column-e 2
  |---row-s 2|row-end ---|
  |  column-e|column-s 2
  |-------row-e 2--------|

隐式网格
  • grid-auto-rows
  • grid-auto-columns
  • grid-auto-flow:网格流向,默认为 row 也可以设置为 column
.warp {
  grid-template-rows: 50px;
  grid-template-columns: repeat(2, 2fr);
  grid-auto-rows: 200px;
}
/* 效果是:如果子元素有多个,第一行的高度为 50px,其它行的元素高度则是 200px */
隐式命名网格线名称?不太懂为什么要这样,我就不写了。
通过 z-index 来确定层级关系
网格项目的对齐方式
  • 网格布局容器
    • justify-items:横向
    • align-items:纵向
  • 子元素自身
    • justify-self
    • align-self
  • 有以下属性:
    • auto
    • normal
    • start 网格线为 1
    • end 网格线为 n
    • center 居中
    • stretch 铺满整行或者整列
网格内容的对齐方式
  • align-content:纵向
  • justify-content:横向
  • 属性:
    • normal
    • start:靠网格布局大小起始边
    • end:靠网格布局大小结束边
    • center:居中
    • space-around:相当于 item 加上左右外边距,外边距不重叠
    • space-between:起始和结束位置的 item 靠边,其他等边距
    • space-evenly:所有 item 都等边距

参考资料

axios 文档

axios

Promise based HTTP client for the browers and Node.js

install axios

npm i -S axios

发送请求

// index.js

let axios = requrie('axios')

// get 请求
axios.get('/user?id=123')
    .then(res => console.log(res))
    .catch(err => console.log(err))

// 或者这样 
axios.get('/user', {
    params: {
        id: 123
    }
})
.then(res => console.log(res))
.catch(err => console.log(err))

// post 请求
axios.post('/user', {
    name: 'tao',
    age: 20
})
.then(res => console.log(res))
.catch(err => console.log(err))

// 使用 Promise.all() 发送多个并发请求
function getName() {
    return axios.get('/user/123/name')
}

function getAge() {
    return axios.get('/user/123/age')
}

axios.all([getName(), getAge()])
    .then(axios.spread((acct, perms) => {

    }))

axios API

axios(config)

// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})

// GET request for remote image
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
      //  pipe() 和 fs.createWriteStream() 应该是 Node.js 
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios(url[, config])

// Send a GET request (default method)
axios('/user/12345');

请求的别名方法

为了方便使用,不必再去配置 config,简化了操作。

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

解决并发请求

  • axios.all(iterable)
  • axios.spread(callback)

自己创建一个 axios 实例

axios.create([config])

let instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Note: 实例的别名方法会根据实例的 config 去合并。

请求的配置项

只有 url 是必须项,默认请求方法为 GET

{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000,

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content allowed
  maxContentLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' defines the hostname and port of the proxy server
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  })
}

响应信息

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  // All header names are lower cased
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}
  • 使用 then:获取返回的响应信息 response
  • 使用 catch:捕获请求错误信息
// 向 url 发送一个 GET 请求,若成功返回的响应信息 res 打印出来,若失败了,则打印出错误信息 err。
axios.(url)
    .then(res => console.log(res))
    .catch(err => console.log(err))

默认配置

你可以规定默认设置,然后所有请求都会使用该配置。

直接使用全局配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

在新建的 axios 实例里设定

// Set config defaults when creating the instance
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置项的优先级

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former.

lib/defaults.js 的配置项 < axios 实例的配置项 < 请求里头的配置项

PS:还有一部分,可我不想写了。。

参考资料

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.