一:click事件300毫秒延迟
// 提下载 npm install fastclick
import fastClick from 'fastclick'
document.addEventListener('DOMContentLoaded', function() {
fastClick.attach(document.body)
})
二:一像素边框
需要js和css同时使用(媒体查询的device-pixel-ratio兼容性堪忧,
所以建议使用此方法,本人亲测好用)
js:
if ('devicePixelRatio' in window) {
let ratio = window.devicePixelRatio
doc.style.setProperty('--ratio', ratio)
}
css
/* css中,:root指的是html标签,在:root中以 -- 开头的属性可以
当做变量使用,使用css的var()函数可以调用该函数,
使用该值进行运算时,需要其中一个值带单位 */
.border { //在html中加入该类名,然后在需要加边框的元素的after伪类
//中直接书写边框的即可
position: relative;
&:after {
content: '';
position: absolute;
left: 0px;
top: 0px;
box-sizing: border-box;
display: block;
transform-origin: 0 0;
width: calc(var(--ratio) * 100%);
height: calc(var(--ratio) * 100%);
transform: scale(calc(1 / var(--ratio)));
}
}
需要添加边框的html标签的样式为:
```javascript
div:after {
//子元素需要设置定位和z-index来实现事件得相应
border-right: 1px solid red;
border-top: 1px solid red;
}
三:设置rem:
/*获取屏幕视图的宽度*/
let doc = document.documentElement
function getClientWidth() {
return doc.clientWidth || window.innerWidth || document.body.clientWidth
}
function setRem() {
let clientWidth = getClientWidth()
let fontSize = 100 //100是为了方便计算 比如16px就是0.16rem,计算方便
let myScreenWidth = 375
doc.style.fontSize = (clientWidth / myScreenWidth) * fontSize + 'px'
}
setRem()
window.addEventListener('resize', setRem)
四:监听页面显示与隐藏
// 安卓
document.addEventListener("visibilitychange", function() {
if (document.visibilityState === "visible") {
this.getWillOpenOrder()
}
})
// ios pagehide | pageshow
window.addEventListener("pageshow", () => {alert("页面显示")})
五:一些小的细节点或技巧
css:
/*多行显示省略号 兼容性不太好 */
.multiline{
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
word-break: break-all;
}
渐变色文字
.text{
background: linear-gradient(90deg, #FF2A2A,#F139D2);
background-clip: text;
color: transparent;
}
优化滑动效果
css{
-webkit-overflow-scrolling: touch;
}
js
获取document.documentElement的scrollTop的兼容写法
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
当某个容器有左右滑动事件时,最好加上touchmove事件,
可以防止浏览器的前后页面的切换,
即使业务本身不需要touchmove事件
页面外层容器不要使用fixed,此属性有时候会导致页面滚动失效,即使设置了overflow:auto
html和body要么都不设置overflow要么都设置,放置意外情况出现,都设置时触发body的scroll事件,都不设置时触发documentElement和window的scroll事件
iPhone端设置fixed的元素,如果父级设置了overflow,那么fixed的元素在下拉或者上卡出现浏览器黑边时可能会被遮挡
//移动端也可以打印(console)需要安装 npm install vconsole -D
import Vconsole from ‘vconsole’
new Vconsole()