前端小知识11点(2019.12.11)

134 阅读8分钟

1、Chrome浏览器全屏显示及监听
主要是几个关键的浏览器 API:
① 判断浏览器是否是全屏

document.webkitIsFullScreen  // true/false

② 全屏

document.documentElement.webkitRequestFullScreen()

③ 退出全屏

//注意:不是 document.documentElement
document.exitFullscreen()

④ 添加全屏切换时的监听事件

window.addEventListener('webkitfullscreenchange', yourfunction );

根据这几个就能控制及监听浏览器的全屏行为

2、获取任意两个日期之间所在的月或年的集合(moment.js)
逻辑代码:

  //两个日期之间所在的月、年
  const getBetweenMonthsOrYearsArray=(startDate, endDate,monthOrYear)=> {
    //给定返回的日期格式
    const dateFormat=monthOrYear==='month'?"YYYY-MM":"YYYY"
    //获取 开始日期 的月或年
    let startMonthOrYear = moment(startDate).startOf(monthOrYear).format(dateFormat);
    //获取 结束日期 的月或年
    const endMonthOrYear = moment(endDate).startOf(monthOrYear).format(dateFormat);
    //日期之间月或年的集合
    const monthOrYearArray = [];
    //循环将月/年 push进数组中,直到开始日期比结束日期大
    while (startMonthOrYear <= endMonthOrYear) {
      console.log(startMonthOrYear,endMonthOrYear,'endMonthOrYear97')
      monthOrYearArray.push(startMonthOrYear);
      startMonthOrYear = moment(startMonthOrYear).add(1, monthOrYear).format(dateFormat);
    }
    //返回结果
    return monthOrYearArray;
  }

例:

  getBetweenMonthsOrYearsArray('2018-05-17','2019-02-01','year') //["2018""2019"]

  getBetweenMonthsOrYearsArray('2018-05-17','2019-02-01','month'
  //["2018-05""2018-06""2018-07""2018-08""2018-09""2018-10""2018-11""2018-12""2019-01""2019-02"]

3、当日期为周日时,获取所在周的周日,出现的bug(moment.js)

  let date='2019-08-11'
  //获取该日期所在的周几
  const n = moment(date, 'YYYY-MM-DD').format('E'// '7'

  //获取所在年的第几周
  //如果是周日(7)的话,周数需要加 1,否则算的是上周!! 
  const end_weeknumber = n==='7'?moment(date).isoWeek()+1:moment(date).isoWeek()

  const end_condition = moment(date)
    .week(+end_weeknumber)
    .isoWeekday(7)
    .format('YYYY-MM-DD')  //'2019-08-11'

特别特别需要注意的就是,当所选日期是周日的时候,获取所在的周数是需要加 1 的

配合 前端小知识10点(2019.9.29) 的第一点使用:

完美版:

let date='2019-08-11'  
let when=0  
const n = moment(date'YYYY-MM-DD').format('E') 
const weeknumber= n==='7'?moment(date).isoWeek()+1:moment(date).isoWeek()

const startDate=moment(date)    
      .week(+weeknumber+when)    
      .isoWeekday(1)    
      .format('YYYY-MM-DD');  //2018-12-31  

const endDate=moment(date)    
      .week(+weeknumber+when)    
      .isoWeekday(7)    
      .format('YYYY-MM-DD');  //2019-01-06

4、在web页面显示LCD液晶字体
参考:页面显示LCD液晶字体,特殊字体,@font-face属性详细用法

但里面废话比较多,这么写就够了:

效果图:

5、absolute垂直居中和水平居中

.a {
    position: absolute;
    top50%;
    left50%;
    transformtranslateX(-50%) translateY(-50%);
 }

6、动态显示时间(React)

class updateTime extends Component {
  state = {
    time'',
  };

  componentDidMount() {
    this.calculTime();
  }

  calculTime = () => {
    const that = this;
    // 当前时间
    this.setState({
      time: moment().format('YYYY年M月D日, h:mm:ss A'),
    });

    // 延迟一秒执行自己
    setTimeout(() => {
      that.calculTime();
    }, 1000);
  };

render() {

  }
}

最好是单独做成一个组件不断更新

7、引用leaflet的扩展包

之前不懂怎么引用扩展包,写成这个样子:

import L from "leaflet-editable";

import L from "leaflet";
import LL from "leaflet-editable";

这些都是不对的,正确引用:

import L from "leaflet";
import "leaflet-editable";
import "leaflet-path-drag";

8、给定两个颜色,获取一定数量的渐变色

  // min rgba(155,224,178,1) max rgba(255,152,0,1)
  //startColor 起始底色
  //endColor 最亮的颜色
  //number 待染色的个数
  function fColorGradualChange(
    //[155,224,178,1]
    startColorArr,
    //[255,152,0,1]
    endColorArr,
    //3
    number
  
{
    //红
    const startR = startColorArr[0];
    //绿
    const startG = startColorArr[1];
    //蓝
    const startB = startColorArr[2];
    //红
    const endR = endColorArr[0];
    //绿
    const endG = endColorArr[1];
    //蓝
    const endB = endColorArr[2];
    //计算每个色阶的平均值
    const sR = (endR - startR) / number;
    const sG = (endG - startG) / number;
    const sB = (endB - startB) / number;

    const colors = [];
    for (let i = 0; i < number; i++) {
      colors.push(
        fColorToHex(
          //每个item 分配得到的 R、G、B
          parseInt(sR * i + startR, 10),
          parseInt(sG * i + startG, 10),
          parseInt(sB * i + startB, 10)
        )
      );
    }
    return colors;
  }

  //rgb转hex
  function fColorToHex(r, g, b{
    const hex =
      "#" +
      // numObj.toString([radix]) 默认转 10 进制,
      // 此处是转为 16 进制
      fAddZero(r.toString(16)) +
      fAddZero(g.toString(16)) +
      fAddZero(b.toString(16));
    //返回拼接的十六进制颜色码
    return hex;
  }

  // 加0补位
  function fAddZero(value{
    //value是0 位、1 位或两位的 16 进制数字
    const newv = "00" + value;
    return newv.substring(newv.length - 2, newv.length);
  }

例:

  <div>
    <div class="a">aaa</div>
    <div class="a">bbb</div>
    <div class="a">ccc</div>
    <div class="a">ddd</div>
    <div class="a">eee</div>
  </div>

  const colorArr=fColorGradualChange([155,224,178,1],[255,152,0,1],5)

  $('.a').each((index,item)=> {
    item.style.color=colorArr[index]
  })

效果:

9、防抖函数
只有在最后一次触发事件的时候才会执行,
比如在不断拖动(dragging)的事件中采用防抖函数:

let timeoutId=0

'dragging':(e:object) =>{
            clearTimeout(timeoutId)
            timeoutId=window.setTimeout(()=>{
              //do something
              //...
            },100)
          },

这个知识在自己的项目里还是挺有用的,一个是拖拽,另一个是鼠标滚轮滚动里也用到过

10、获取网页缩放比例

window.devicePixelRatio

11、控制input光标的位置——setSelectionRange
文档参考:
developer.mozilla.org/zh-CN/docs/…

例1:
单个 input 选择一段值

<input type="text" id="inputa" value="123456789" />

document.getElementById('inputa').focus()
document.getElementById('inputa').setSelectionRange(2,5)

例 2:
多个 input 联动,跳光标

<input type="text" id="inputa" value="" oninput="setInput()"/>
<input type="text" id="inputb" value="34"/>

const a=document.getElementById('inputa')
const b=document.getElementById('inputb')

  function setInput() {
    if (a.value.length === 2) {
      b.focus()
      b.setSelectionRange(33)
    }
  }

inputa 输入 2 个值后,光标自动跳到inputb 的值的最后:


(完)