JS代码片段
打印浏览器信息
1 2 3 4 5 6 7 8 9 10 11 12
| document.write("CodeName=" + navigator.appCodeName + "<br />"); document.write("MinorVersion=" + navigator.appMinorVersion + "<br />"); document.write("Name=" + navigator.appName + "<br />"); document.write("Version=" + navigator.appVersion + "<br />"); document.write("CookieEnabled=" + navigator.cookieEnabled + "<br />"); document.write("CPUClass=" + navigator.cpuClass + "<br />"); document.write("OnLine=" + navigator.onLine + "<br />"); document.write("Platform=" + navigator.platform + "<br />"); document.write("UserAgent=" + navigator.userAgent + "<br />"); document.write("BrowserLanguage=" + navigator.browserLanguage + "<br />"); document.write("SystemLanguage=" + navigator.systemLanguage + "<br />"); document.write("UserLanguage=" + navigator.userLanguage + "<br />");
|
判断浏览器类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var browser = { versions: function () { var u = navigator.userAgent, app = navigator.appVersion; return { trident: u.indexOf('Trident') > -1, presto: u.indexOf('Presto') > -1, webKit: u.indexOf('AppleWebKit') > -1, gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, mobile: !!u.match(/AppleWebKit.*Mobile.*/), ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, iPhone: u.indexOf('iPhone') > -1 , iPad: u.indexOf('iPad') > -1, webApp: u.indexOf('Safari') == -1, weixin: u.indexOf('MicroMessenger') > -1, qq: u.match(/\sQQ/i) == " qq" } }(), language:(navigator.browserLanguage || navigator.language).toLowerCase() }
|
参考: 通过浏览器navigator判断浏览器版本或者手机类型&&判断微信访问
获取数组中最大最小值
1 2 3 4 5
| let arr = [5,6,4,3,9,2] const arrMax = arr => Math.max(...arr) const arrMin = arr => Math.min(...arr) console.log(arrMax(arr)) console.log(arrMin(arr))
|
阻止元素默认行为
1 2 3 4 5 6 7 8 9 10 11 12
| function stopDefault( e ) { if ( e && e.preventDefault ) { e.preventDefault(); } else { window.event.returnValue = false; } return false; }
|
阻止事件冒泡
1 2 3 4 5 6 7 8 9 10 11
| function stopBubble(e) { if ( e && e.stopPropagation ) { e.stopPropagation(); } else { window.event.cancelBubble = true; } }
|
参考: JavaScript停止冒泡和阻止浏览器默认行为
获取指定名称的Cookie
1 2 3 4 5
| function findCookie (key) { let reg = new RegExp('(^| )' + key + '=([^;]*)(;|$)', 'i') let values = document.cookie.match(reg) return values !== null ? decodeURIComponent(values[2]) : null }
|
获取所有的Cookie
1 2 3 4 5 6 7 8 9
| function getCookies() { let cookie = document.cookie return cookie.split(';').map(e => { let cookieObj = {} cookieObj.key = e.split('=')[0] cookieObj.value = e.split('=')[1] return cookieObj }) }
|
删除指定名称的Cookie
1 2 3 4 5 6
| function delCookie (name) { let exp = new Date() exp.setTime(exp.getTime() - 1) let cval = findCookie(name) cval !== null && (document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()) }
|
设置指定名称的Cookie
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| function getsec (str) { let str1 = str.substring(0, str.length - 1) * 1 let str2 = str.substring(str.length - 1, str.length) return str2 === "s" && str1 * 1000 || str2 === "h" && str1 * 60 * 60 * 1000 || str2 === "d" && str1 * 24 * 60 * 60 * 1000 } function setCookie (name, value, time) { let strsec = getsec(time) let exp = new Date() exp.setTime(exp.getTime() + strsec * 1) document.cookie = name + "=" + decodeURIComponent(value) + ";expires=" + exp.toGMTString() } setCookie('name', 'xiaoyu', '60s')
|
获取指定名称的地址栏参数
1 2 3 4 5
| function getUrlParm (key) { let reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i') let values = window.location.search.substr(1).match(reg) return values !== null ? decodeURIComponent(values[2]) : null }
|
获取所有的地址栏参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| function getUrlParams () { let url = location.search if (url) { let theRequestMap = new Map() if (url.indexOf('?') !== -1) { let str = url.substr(1) let strs = str.split('&') for (let i = 0; i < strs.length; i++) { theRequestMap[strs[i].split('=')[0]] = decodeURIComponent(strs[i].split('=')[1]) } } return theRequestMap } else { return null } }
|
localstorage操作
1 2 3
| localStorage.setItem('date', 20) localStorage.getItem('date') localStorage.removeItem('date')
|
友好的时间显示脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| export default function (time, withTime = false) { let date = (time instanceof Date) ? time : (typeof time === 'number') ? new Date(time) : new Date((time || '').replace(/-/g, '/')) let diff = (((new Date()).getTime() - date.getTime()) / 1000) let dayDiff = Math.floor(diff / 86400) let isValidDate = Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime()) if (!isValidDate) { console.error('not a valid date') } const formatDate = function (date, withTime) { let today = new Date(date) let year = today.getFullYear() let month = ('0' + (today.getMonth() + 1)).slice(-2) let day = ('0' + today.getDate()).slice(-2) let hour = today.getHours() let minute = today.getMinutes() let second = today.getSeconds() return withTime ? `${year}-${month}-${day} ${hour}:${minute}:${second}` : `${year}-${month}-${day}` } if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 30) { return formatDate(date, withTime) } return dayDiff === 0 && ( diff < 60 && '刚刚' || diff < 120 && '1分钟前' || diff < 3600 && Math.floor(diff / 60) + '分钟前' || diff < 7200 && '1小时前' || diff < 86400 && Math.floor(diff / 3600) + '小时前') || dayDiff === 1 && '昨天' || dayDiff < 7 && dayDiff + '天前' || dayDiff < 30 && Math.ceil(dayDiff / 7) + '周前' }
|
格式化时间显示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| export default function (date, fmt = 'YYYY-MM-DD HH:mm:ss') { date = typeof date === 'number' ? new Date(date) : date var o = { 'M+': date.getMonth() + 1, 'D+': date.getDate(), 'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, 'H+': date.getHours(), 'm+': date.getMinutes(), 's+': date.getSeconds(), 'q+': Math.floor((date.getMonth() + 3) / 3), 'S': date.getMilliseconds() } var week = { '0': '\u65e5', '1': '\u4e00', '2': '\u4e8c', '3': '\u4e09', '4': '\u56db', '5': '\u4e94', '6': '\u516d' } if (/(Y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) } if (/(E+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '\u661f\u671f' : '\u5468') : '') + week[date.getDay() + '']) } for (var k in o) { if (new RegExp('(' + k + ')').test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length))) } } return fmt }
|
CSS代码片段
单行文本溢出显示省略号
1 2 3
| overflow: hidden; text-overflow:ellipsis; white-space: nowrap;
|
多行文本溢出显示省略号
1 2 3 4 5
| display: -webkit-box; overflow : hidden; text-overflow: ellipsis; -webkit-box-orient: vertical; -webkit-line-clamp: 2;
|
display: -webkit-box : 必须结合的属性 ,将对象作为弹性伸缩盒子模型显示
-webkit-box-orient : 必须结合的属性 ,设置或检索伸缩盒对象的子元素的排列方式
-webkit-line-clamp : 必须结合的属性 ,用来限制在一个块元素显示的文本的行数。
参考: css实现单行、多行文本溢出显示省略号(…)
针对苹果手机页面滚动不流畅的处理
1
| -webkit-overflow-scrolling : touch;
|
原理: 实际上在iOS系统的手机上创建了一个UIWebOverflowScrollView,它继承自UIScrollView,使得滚动具有”橡皮筋特效”
参考: 网页在Safari快速滚动和回弹的原理: -webkit-overflow-scrolling : touch;的实现
使用 :not() 在菜单上应用/取消应用边框
一般我们会这么写,先给每一个菜单项添加边框,然后再除去最后一个元素
1 2 3 4 5 6
| .nav li { border-right: 1px solid #666; } .nav li:last-child { border-right: none; }
|
其实可以直接使用 :not() 伪类来应用元素:
1 2 3
| .nav li:not(:last-child) { border-right: 1px solid #666; }
|
或者使用兄弟选择器:
1 2 3
| ul>li~li { border-top: 1px solid #000; }
|
或者:
1 2 3
| ul>li+li { border-top: 1px solid #000; }
|
参考: 20 个 CSS 高级技巧汇总
给页面顶部添加阴影
1 2 3 4 5 6 7 8 9 10 11 12
| body:before { content: ""; position: fixed; top: -10px; left: 0; width: 100%; height: 10px; -webkit-box-shadow: 0px 0px 10px rgba(0,0,0,.8); -moz-box-shadow: 0px 0px 10px rgba(0,0,0,.8); box-shadow: 0px 0px 10px rgba(0,0,0,.8); z-index: 100; }
|
使用逗号分割列表
1 2 3
| ul > li:not(:last-child)::after { content: ","; }
|
使用属性选择器用于空链接
当a元素没有文本值,但 href 属性有链接的时候显示链接:
1 2 3
| a[href^="http"]:empty::before { content: attr(href); }
|
使用CSS书写三角形
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| div.arrow-up { width:0px; height:0px; border-left:5px solid transparent; border-right:5px solid transparent; border-bottom:5px solid #2f2f2f; font-size:0px; line-height:0px; } div.arrow-down { width:0px; height:0px; border-left:5px solid transparent; border-right:5px solid transparent; border-top:5px solid #2f2f2f; font-size:0px; line-height:0px; } div.arrow-left { width:0px; height:0px; border-bottom:5px solid transparent; border-top:5px solid transparent; border-right:5px solid #2f2f2f; font-size:0px; line-height:0px; } div.arrow-right { width:0px; height:0px; border-bottom:5px solid transparent; border-top:5px solid transparent; border-left:5px solid #2f2f2f; font-size:0px; line-height:0px; }
|
禁用鼠标点击事件
1
| .disabled { pointer-events: none; }
|
模糊文本
1 2 3 4
| .blur { color: transparent; text-shadow: 0 0 5px rgba(0,0,0,0.5); }
|
HTML代码片段
viewport
1
| <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
|
禁止页面缓存
1 2 3
| <meta http-equiv="Pragma" CONTENT="no-cache"/> <meta http-equiv="Cache-Control" CONTENT="no-cache"/> <meta http-equiv="Expires" CONTENT="0"/>
|
accesskey
accesskey属性可以为input添加快捷键
1 2 3 4 5
| <form action=""> <p>Name: <input type="text" accesskey="1"></p> <p>Password: <input type="password" accesskey="2"></p> <p>submit: <input type="submit" accesskey="3"></p> </form>
|
具体快捷键如下:
| 浏览器 / 平台 |
Window |
Linux |
Mac |
| Firefox |
Alt + Shift + key |
Alt + Shift + key |
Control + Alt + key |
| Internet Explorer |
Alt + key |
N/A |
N/A |
| Google Chrome |
Alt + key |
Alt + key |
Control + Alt + key |
| Safari |
Alt + key |
N/A |
Control + Alt + key |
| Opera |
同 Google Chrome |
同 Google Chrome |
同 Google Chrome |
tabindex
tabindex可以使用Tab按键切换元素。
1 2 3 4 5 6
| <form action=""> <label>Name: <input type="text" tabindex="1"></label> <label>City: <input type="text" tabindex="2"></label> <label>Country: <input type="text" tabindex="3"></label> <input type="submit" value="submit" tabindex="4"> </form>
|
参考: HTML5全局属性汇总
contenteditable
使用contenteditable="true"使元素可访问
1
| <p contenteditable="true">设置为 true 是可编辑的</p>
|
dir
dir 属性用来规定元素中文字的方向。
1 2
| <p dir="ltr">从左到右</p> <p dir="rtl">从右到左</p>
|
各种居中方式
内容垂直居中
相邻元素垂直居中
注意: 仅适用于行内块元素。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| div.one { width: 300px; height: 300px; background-color: #f00; display: inline-block; vertical-align: middle; } div.two { width: 200px; height: 200px; background-color: #0f0; display: inline-block; vertical-align: middle; }
|
内容水平居中
盒子居中
注意: 得指定盒子宽度,适用于块元素。
弹性盒子
1 2 3
| display: flex; justify-content: center; align-item: center;
|
定位居中
1 2 3 4 5
| position: absolute; top: 2em; bottom: 2em; left: 2em; right: 2em;
|
Last updated:
这里可以写作者留言,标签和 hexo 中所有变量及辅助函数等均可调用,示例:
http://blog.quanzaiyu.top/2022/09/06/常用前端代码片段整理/