正文
-
试试给div加上contentEditable = true
-
如何获取当前页面的滚动位置?
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}
- 如何平滑滚动到页面顶部
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop
if (c > 0) {
window.requestAnimationFrame(scrollToTop)
window.scrollTo(0, c - c / 8)
}
}
// 事例
scrollToTop()
- 如何检查指定的元素在视口中是否可见?
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect()
const { innerHeight, innerWidth } = window
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth
}
// 事例
elementIsVisibleInViewport(el) // 需要左右可见
elementIsVisibleInViewport(el, true) // 需要全屏(上下左右)可以见
- 如何确定设备是移动设备还是台式机/笔记本电脑?
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop'
// 事例
detectDeviceType() // "Mobile" or "Desktop"
- 如何创建一个包含当前URL参数的对象?
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
)
// 事例
getURLParameters('http://url.com/page?n=Adam&s=Smith') // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com') // {}
- 如何将字符串复制到剪贴板?
const copyToClipboard = str => {
const el = document.createElement('textarea')
el.value = str
el.setAttribute('readonly', '')
el.style.position = 'absolute'
el.style.left = '-9999px'
document.body.appendChild(el)
const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false
el.select()
document.execCommand('copy')
document.body.removeChild(el)
if (selected) {
document.getSelection().removeAllRanges()
document.getSelection().addRange(selected)
}
}
// 事例
copyToClipboard('Lorem ipsum')
// 'Lorem ipsum' copied to clipboard
- 如何在gif动画播放完成之后继续播放下一张? 可通过gif.js(3.8k star)对img标签进行监听
官方示例:
var gif = new GIF({
workers: 2,
quality: 10
});
// add an image element
gif.addFrame(imageElement);
// or a canvas element
gif.addFrame(canvasElement, {delay: 200});
// or copy the pixels from a canvas context
gif.addFrame(ctx, {copy: true});
gif.on('finished', function(blob) {
window.open(URL.createObjectURL(blob));
});
gif.render();
在线Demo戳jnordberg.github.io/gif.js
- 如何在ts中判断变量是否为自定义类型
const isType = <T>(param: unknown, judgement: boolean): param is T => judgement
例子:
type testT = {
propsA: string
propsB: string
}
const a = { propsA: 'test' }
console.log(isType<testT>(a, a.hasOwnProperty('propsA'))) // true