web建站教程

  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. php入门
    nodejs
    mockjs
    mysql
    织梦cms
    帝国cms
    git教程

前端19个冷知识代码

58 ℃

下面web建站教程为大家介绍一下前端19个冷知识代码

1. 获取当前页面的滚动位置

const getScrollPosition = (el = window) => ({ 
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 
}) 
getScrollPosition(); // {x: 0, y: 200}

2. 平滑滚动到页面顶部

const scrollToTop = () => { 
    const c = document.documentElement.scrollTop || document.body.scrollTop 
    if (c > 0) { 
        window.requestAnimationFrame(scrollToTop) 
        window.scrollTo(0, c - c / 8) 
    } 
} 
scrollToTop()

3. 确定设备是移动设备还是台式机/笔记本电脑

const detectDeviceType = () => 
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
    .test(navigator.userAgent) ? 
    'Mobile' : 'Desktop' 
detectDeviceType() // "Mobile" or "Desktop"

4. 带图带事件的桌面通知

function doNotify(title, options = {}, events = {}) {
  const notification = new Notification(title, options)
  for (let event in events) {
    notification[event] = events[event]
  }
}

function notify(title, options = {}, events = {}) {
  if (!('Notification' in window)) {
    return console.error('This browser does not support desktop notification')
  } else if (Notification.permission === 'granted') {
    doNotify(title, options, events)
  } else if (Notification.permission !== 'denied') {
    Notification.requestPermission().then(function (permission) {
      if (permission === 'granted') {
        doNotify(title, options, events)
      }
    })
  }
}
notify(
  '中奖提示',
  {
    icon: 'https://sf1-ttcdn-tos.pstatp.com/img/user-avatar/f1a9f122e925aeef5e4534ff7f706729~300x300.image',
    body: '恭喜你,掘金签到一等奖',
    tag: 'prize'
  },
  {
    onclick(ev) {
      console.log(ev)
      ev.target.close()
      window.focus()
    }
  }
)

5. 数组转树

function treeDataTranslate(data, id = 'id', pid = 'pId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

6. 禁用在浏览器打开控制台

setInterval(function () {
  check()
}, 4000)
var check = function () {
  function doCheck(a) {
    if (('' + a / a)['length'] !== 1 || a % 20 === 0) {
      ;(function () {}['constructor']('debugger')())
    } else {
      ;(function () {}['constructor']('debugger')())
    }
    doCheck(++a)
  }
  try {
    doCheck(0)
  } catch (err) {}
}
check()

7. 函数柯里化

function add() {
  let args = [...arguments]
  function _add() {
      args.push(...arguments)
      return _add
  }
  _add.toString = function () {
      return args.reduce((pre, cur) => {
          return pre + cur
      })
  }
  return _add
}
console.log(add(1, 2)(3, 4)(5)(6)()().toString())

8. toFullScreen:全屏

function toFullScreen() {
  let elem = document.body
  elem.webkitRequestFullScreen
    ? elem.webkitRequestFullScreen()
    : elem.mozRequestFullScreen
    ? elem.mozRequestFullScreen()
    : elem.msRequestFullscreen
    ? elem.msRequestFullscreen()
    : elem.requestFullScreen
    ? elem.requestFullScreen()
    : alert('浏览器不支持全屏')
}

9. exitFullscreen:退出全屏

function exitFullscreen() {
  let elem = parent.document
  elem.webkitCancelFullScreen
    ? elem.webkitCancelFullScreen()
    : elem.mozCancelFullScreen
    ? elem.mozCancelFullScreen()
    : elem.cancelFullScreen
    ? elem.cancelFullScreen()
    : elem.msExitFullscreen
    ? elem.msExitFullscreen()
    : elem.exitFullscreen
    ? elem.exitFullscreen()
    : alert('切换失败,可尝试Esc退出')
}

10. 禁止右键、选择、复制

;['contextmenu', 'selectstart', 'copy'].forEach(function (ev) {
  document.addEventListener(ev, function (event) {
    return (event.returnValue = false)
  })
})

11. 首字母大写

let firstUpperCase = ([first, ...rest]) => first?.toUpperCase() + rest.join('')

12. 数据类型验证

function typeOf(obj) {
  const toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object FormData]': 'formData',
    '[object Symbol]': 'symbol', 
    '[object BigInt]': 'bigint'
  }
  return map[toString.call(obj)]
}

13. 复制文本

copyPersonURL(content) {
  let that = this
  if (window.ClipboardData) {
      window.clipboardData.setData('text', content)
  } else {
      ;(function (content) {
          document.oncopy = function (e) {
              e.clipboardData.setData('text', content)
              e.preventDefault()
              document.oncopy = null
          }
      })(content)
      document.execCommand('Copy')
  }
}

14.docx文件转html

部分样式无法实现,所以最好还是后端去实现,后端的比较成熟,这里用vue来演示
需要安装插件mammoth
npm install mammoth --save

<input type="file" name="file" @change="changeFile" />

<div id="wordView" v-html="wordText" />

import mammoth from "mammoth" //选择本地文件预览 changeFile(event) { // if(event.target.files[0].name.indexOf('docx')>-1){ let that = this; let file = event.target.files[0]; let reader = new FileReader(); reader.onload = function (loadEvent) { let arrayBuffer = loadEvent.target.result; //arrayBuffer mammoth .convertToHtml({ arrayBuffer: arrayBuffer }) // .convertToMarkdown({ arrayBuffer: arrayBuffer }) .then(that.displayResult) .done(); }; reader.readAsArrayBuffer(file); // } }, //页面渲染 displayResult(result) { console.log(result.value) this.wordText = result.value; }

15.验证'()'是否成对出现

[..."(())()(()())"].reduce((a,i)=> i === '(' ? a+1 : a-1 , 0);
// 输出0则是 

16.判断当前标签页是否激活

const isTabInView = () => !document.hidden

17.打开浏览器打印

const showPrintDialog = () => window.print()

18.html转图片

需要安装插件dom-to-image
npm install dom-to-image
//引入domtoimage
import domtoimage from 'dom-to-image';
downLoadPhoto () {
  const node = document.getElementById('table')//对应的html标签id
  domtoimage.toPng(node)
    .then((dataUrl) => {
      const img = new Image()
      img.src = dataUrl
      // 将获取到的base64下载下来
      const imgUrl = img.src
      if (window.navigator.msSaveOrOpenBlob) {
        const bstr = atob(imgUrl.split(',')[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
        }
        const blob = new Blob([u8arr])
        window.navigator.msSaveOrOpenBlob(blob, 'chart-download' + '.' + 'png')
      } else {
        // 这里就按照chrome等新版浏览器来处理
        const a = document.createElement('a')
        a.href = imgUrl
        a.setAttribute('download', 'chart-download')
        a.click()
      }
    })
}

19.字符串转base与base64转字符串

// 加密
function base64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}
// 解密
function base64DecodeUnicode(str) {
    return decodeURIComponent(atob(str).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

实现知乎滑动效果介绍(附html+js代码)

前端常用的49个JavaScript方法

20个JavaScript开发小技巧

前端冷知识:25个正则表达式

上面是“前端19个冷知识代码”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_1495.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

js获取本周/本月/本季的起始时间、结束时间及本月天数

var now = new Date(); // 当前日期
var nowDayOfWeek = now.getDay(); // 今天是本周的第几天
var nowDay = now.getDate(); // 当前日
var nowMonth = now.getMonth(); // 当前月
var nowYear = now.getYear(); // 当前年
nowYear += (nowYear < 2000) ? 1900 : 0;
var getDate = {
  /*获得当前日期*/
  getNowDay() {
  	return this.formatDate(new Date());
  },
  /*获得本周的开始时间*/
  getStartDayOfWeek() {
  	var day = nowDayOfWeek || 7;
  	return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));
  },
  /*获得本周的结束时间*/
  getEndDayOfWeek() {
  	var day = nowDayOfWeek || 7;
  	return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 7 - day));
  },
  /*获得本月的开始时间*/
  getStartDayOfMonth() {
  	var monthStartDate = new Date(nowYear, nowMonth, 1);
  	return this.formatDate(monthStartDate);
  },
  /*获得本月的结束时间*/
  getEndDayOfMonth() {
  	var monthEndDate = new Date(nowYear, nowMonth, this.getMonthDays());
  	return this.formatDate(monthEndDate);
  },
  /*获得本月天数*/
  getMonthDays() {
    var monthStartDate = new Date(nowYear, nowMonth, 1);
    var monthEndDate = new Date(nowYear, nowMonth + 1, 1);
    var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
    return days;
  },
  /*获得本季度开始*/
  getQuarterStart(){
    let m = 0;
    if(nowMonth<3){//012
        m = 0
    }else if(28){ //9 10 11
        m = 9
    }
    let quarterStart = new Date(nowYear,m,1)
    return this.formatDate(quarterStart)
  
  },
  /*获得本季度结束*/
  getQuarterEnd :function(){
    let m = 0;
    if(nowMonth<3){//012
    	 m = 3
    }else if(28){ //9 10 11
    	 m = 0
    }
    let quarterEnd = new Date(nowYear,m,1).getTime()-(60*60*24*1000)
    return this.formatDate(new Date(quarterEnd))
  },
  /*日期格式化*/
  formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;
    var myweekday = date.getDate();
    if (mymonth < 10) {
    	mymonth = "0" + mymonth;
    }
    if (myweekday < 10) {
    	myweekday = "0" + myweekday;
    }
    return (myyear + '-' + mymonth + '-' + myweekday);
  }
};
console.log('本周开始时间:',getDate.getStartDayOfWeek())
console.log('本周结束时间:',getDate.getEndDayOfWeek())
console.log('本月开始时间:',getDate.getStartDayOfMonth())
console.log('本月结束时间:',getDate.getEndDayOfMonth())
console.log('本月天数计算:',getDate.getMonthDays())
console.log('本季开始时间:',getDate.getQuarterStart())
console.log('本季结束时间:',getDate.getQuarterEnd())
点击阅读全文
上一篇:js对象找到数组中相同参数插入替换原来的
下一篇:前端33个js知识基础代码