前端 实用的冷门知识 持续更新中......

 少见好用的js API

 

1.类似于jquery中的  toggle()

 // 如果有这个类名,就去掉,如果没有,就加上
        div.classList.toggle("expand");

2.css3中   columns属性实现瀑布流布局  ,多列布局

div
{
    columns:100px 3;   //分成3列  每列100px,如果视口缩小 则列数随之减少
    -webkit-columns:100px 3; /* Safari and Chrome */
    -moz-columns:100px 3; /* Firefox */
}

column-width给列定义个最小的宽度。默认值为auto表示将根据column-count列的数量自动调整列宽。
column-count最大列数
column-gap: 列与列间的间隙, ie下默认为 16px,其它浏览器未明确给出。

column-rule 每列间隙中的竖线

column-span: 元素跨越列数(firefox 不支持)

 3.非css3椭圆形阴影写法

#shadow {
    border-radius: 50%;
    width: 100px;
    height: 100px;
    background: black;
    opacity: 0.5;
    -webkit-filter: blur(10px);
    -webkit-transform: scale(1,0.2);
}

 4.jq去重

$.unique(themeIdArr)

5.数组中的数字字符转为数字

//使用 map 重新格式化数组中的对象
['123','456','789'].map(Number)  //[123,456,789]

 6.判断是否上一页

 function goback(){
        document.referrer === '' ?
          console.log(‘没有上一页时’):
          window.history.go(-1);
    }

注释:判断是否有没有来源信息就是使用这里的document.referrer,当浏览器得不到上一页的来源信息的时候,document.referrer的返回值就是空字符串''

7.判断是否为首次加载

if(window.name == ""){
  console.log("首次被加载");
  window.name = "isReload";  // 在首次进入页面时我们可以给window.name设置一个固定值 
}else if(window.name == "isReload"){
   console.log("页面被刷新");
}

 

8. 将url中的query参数转换为对象

出现的问题:   当div渲染时会直接将最终设定的样式渲染上去  ,  并没有是达到  scale(0)到scale(1)  的效果

function urlToObj(str){
  var obj = {};
  var arr1 = str.split("?");
  var arr2 = arr1[1].split("&");
  for(var i=0 ; i < arr2.length; i++){
    var res = arr2[i].split("=");
    obj[res[0]] = res[1];
  }
  return obj;
}

 

9. js中的强制渲染   getComputedStyle()

出现的问题:   当div渲染时会直接将最终设定的样式渲染上去  ,  并没有是达到  scale(0)到scale(1)  的效果

解决方案 :   getComputedStyle(div).top;  当元素刚添加至页面  就先强制渲染  然后再执行下一行代码 来实现效果

 

//为了实现动画,添加div的时候,要将它设置为最小
    div.style.transform = "translate(-50%, -50%) scale(0)";
    document.body.appendChild(div);
    //强行让浏览器进行渲染:只要出现读取某个元素最终样式(位置、尺寸)的代码
      getComputedStyle(div).top; //这句代码除了让浏览器强行渲染之外,没有任何其他意义

    //将div变回原来的大小
    div.style.transform = "translate(-50%, -50%) scale(1)";

 

10. 通过模拟点击,来扩大点击范围

clickAlabel($('.father02'))
function clickAlabel(target){
    target.on("click",function(e){
        let nodeName = e.target.nodeName;
        if(nodeName !="A"){
            let link = $(this).find("a")[0];
            link.click();
        }
    })
}

 

11. 通过window对象来获取dom元素

 在元素节点上加上 id , window上就会默认将这个id名作为键名 , 值为dom元素

举例:

通过  window.postttt  , 获取到id为 postttt 的元素

 

 

12.监听动画结束

        function AnimationEnd(obj, callback) {
            var call = null;
            obj.addEventListener("animationend", function () {
                callback && callback();
                obj.removeEventListener("animationend", arguments.callee, false);
            }, false);
        };

 

13.js上传代码及显示

$("#upfile").change(function(){
      var objUrl=getURL(this.files[0]);
      if(objUrl){
      $("img").attr("src",objUrl);
   }
 })


      function getUrl(file){
            var url=null;
            if (window.createObjectURL != undefined) {
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) {
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) {
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
      }

 

14.仅用H5和css标签实现点击显示隐藏

<style>
    summary{
        list-style: none;//默认显示箭头
        outline: none;
    }
    
</style>

<details>
     <summary>基本信息</summary>
    用户的基本信息
</details>

 

 

15.利用flex布局实现多行元素,均匀靠边排列

justify-contentspace-between;会将每行都靠边排列,

如果不想最后一行不靠边排列,就将最后一个元素css设置属性为margin-right:auto

16. 判断一个元素内是否包含另一个元素

parentEl.contains(childrenEl) 

例子:

let parent = document.getElementById('parent')
let children = document.getElementById('children')
if (parent.contains(children)) {
  console.log(true)
}
if (children.contains(parent)) {
  console.log(false)
}

 

17. 退出登录后,禁止点击浏览器返回按钮,返回到系统内部页面

 

//退出登录后,禁止点击浏览器返回按钮,返回到系统内部页面
                      history.pushState(null, null, document.URL)
                      window.addEventListener(
                        'popstate',
                        function() {
                          history.pushState(null, null, document.URL)
                        },
                        false
                      )

18. 同步阻塞法实现sleep函数

const sleep = delay => {
    const start = new Date().getTime();
    while (new Date().getTime() < start + delay) {
       continue;
    };
};
console.log(1);
sleep(3000);
console.log(2);

 

19. 全屏

 // 全屏
    requestFullScreen() {
      let element = this.$refs.editor
      var requestMethod =
        element.requestFullScreen ||
        element.webkitRequestFullScreen ||
        element.mozRequestFullScreen ||
        element.msRequestFullScreen
      if (requestMethod) {
        requestMethod.call(element)
      } else if (typeof window.ActiveXObject !== 'undefined') {
        const ActiveXObject = window.ActiveXObject
        var wscript = new ActiveXObject('WScript.Shell')
        if (wscript !== null) {
          wscript.SendKeys('{F11}')
        }
      }
    },
    // 退出全屏
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      }
    },

 

20. 跳转到指定节点

跳转到页面指定元素的位置有一个api,   node.scrollIntoView(true)

你只要用想跳转到的dom调用这个函数就可以了.

其中true和false的传参是决定跳转到节点开始处还是结尾的作用.

 

21. 16进制色值设置反色

/**
 * 16进制色值获取反色设置方法
 * @param  {String} oldColor 为16进制色值的字符串(例:'#000000')
 * @return {String} 返回反色的色值(例:'#ffffff')
 */
const colorReverse = (oldColor) => {
   oldColor = '0x' + oldColor.replace(/#/g, '');
   let str = '000000' + (0xFFFFFF - oldColor).toString(16);
   return '#'+ str.substring(str.length - 6, str.length);
}

 

22. 解析粘贴的文本

 document.querySelectorAll('.paste')[0].addEventListener('paste', event => {
        // 获取解析 粘贴的文本
        let text = (event.clipboardData || window.clipboardData).getData('text')
        if (text.indexOf('\r\n') != -1) {
          event.preventDefault()
          text = text.split('\r\n')
          console.log(text)
        }
      })

 

23. 清除光标对象选中

clearSelections() {
      if (window.getSelection) {
        // 获取选中
        var selection = window.getSelection()
        // 清除选中
        selection.removeAllRanges()
      } else if (document.selection && document.selection.empty) {
        // 兼容 IE8 以下,但 IE9+ 以上同样可用
        document.selection.empty()
        // 或使用 clear() 方法
        // document.selection.clear();
      }
    }

 

24. forEach async和await不起效果 

forEach 只支持同步,不支持异步

1、首先这是因为foreach是没有return返回值的(foreach内部实现只是简单的回调)

2、而foreach里面的回调函数因为加了async的原因,所以默认会返回一个promise,

  但是因为foreach的实现并没有返回值,所以导致返回的这个promise对象没人去管了


换成  for循环 有作用

举例:

async () => {
     this.timer = null
     for (let index = 0; index < this.fileUpload.length; index++) {
             await promise()
    }
}    

 

25. 去除指定eslint校验

问题举例:

 

 

 解决:

//忽略下一行指定的 eslint 校验, no-useless-escape  为eslint校验规则
// eslint-disable-next-line no-useless-escape

 

示例:

 

将整个文件禁用 eslint  ,  /* eslint-disable */

 

 

26. 创建uuid

//创建uuid
createdUuid() {
function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) } return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4() }

27. iframe跨域

iframe跨域问题,导致 iframe 不可操作

 iframe 内部引用资源是相对路径,且路径前缀一样,则  本地可以通过 代理  配置devServer 解决,线上环境同样也需要代理

 

28. 点击触发,自定义触发事件

clickInput() {
      this.$refs.inputFile.dispatchEvent(new MouseEvent('click'))
    },

 

29. 根目录下src文件夹内的文件批量转换尾序列 为:LF

 使用git-windows自带有dos2unix.exe ,  执行 find ./src -type f -exec dos2unix {} \;   
根目录下src文件夹内的文件批量转换尾序列 为:LF。

 

30.点击其他地方,失去选中文本

选中文本后,点击右侧菜单,会失去选中的文本   window.getSelection 对象会被清除掉...

 

被点击的 组件加上  @mousedown.prevent.native=""  就可以解决这个问题

 

问题就解决了

 

 

31.vue监听可编辑div的内容 contenteditable

给可编辑的div 加上   @input  进行监听

 <div :contenteditable="heightOptions.contenteditable || true" @input="e => $emit('handleInputEvent', e)" class="headLine-text" ref="headLine">
    <slot></slot>
  </div>

32.vue可编辑div的内容 contenteditable  请输入提示

可编辑元素加上  :empty::before

32.vue祖孙级slot传递

使用 $slots和  $scopedSlots 接收插槽

  

33.检测元素是否在屏幕中

const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // `entry.target` is the dom element
      console.log(`${entry.target.id} is visible`);
    }
  });
};

const options = {
  threshold: 1.0,
};
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");
observer.observe(btn);
observer.observe(bottomBtn);

 

 34.捕获 async 异常 

  //封装async await
    async test(fn) {
      try {
        let resp = await fn
        return [null, resp]
      } catch (err) {
        return [err, null]
      }
    }

用法示例:

let [err, res] = await this.test(
      getToken().then(res => {
        return res.data.access_token
      })
    )
    if (!err) {
      this.token = res
    } else {
      this.$message.error(err)
    }

 

。。。

 

posted @ 2019-12-17 17:59  混名汪小星  阅读(305)  评论(0编辑  收藏  举报