新手引导动画的4种实现方式
前言
前一陣子忙著找工作,面試過程中,碰到一個(gè)感覺比較有意思的問題,盡量多的列舉出新手引導(dǎo)動畫的實(shí)現(xiàn)方式, 昨天稍微總結(jié)了一下, 實(shí)現(xiàn)了4種.源碼在最后,如果想直接看結(jié)果的,可以拉到最后去看.
這里假設(shè)所有的彈出層都是基于頁面上原有的元素
實(shí)現(xiàn)一 復(fù)制目標(biāo)內(nèi)容
具體步驟:
核心代碼:
let target = document.querySelector('.mid-center') let pos = target.getBoundingClientRect()let clone = target.cloneNode(true)clone.style.position = 'fixed' clone.style.left = pos.left clone.style.top = pos.top clone.style.width = pos.width clone.style.height = pos.height clone.style.zIndex = 100document.body.appendChild(clone) 復(fù)制代碼優(yōu)缺點(diǎn) 比較平凡的實(shí)現(xiàn)方式,普普通通的,沒啥特色.
實(shí)現(xiàn)二 利用box-shadow
具體步驟:
核心代碼:
let target = document.querySelector('.mid-center') target.style.boxShadow = '0 0 0 4000px rgba(0, 0, 0, 0.85)' target.style.position = 'relative' 復(fù)制代碼這里設(shè)置 position:relative 是為了讓 box-shadow 陰影不被父容器所擋住. 如果沒有設(shè)置, box-shadow 會顯示不全
優(yōu)缺點(diǎn)
優(yōu)點(diǎn): 實(shí)現(xiàn)方式簡單易懂
缺點(diǎn): box-shadow 是個(gè)比較耗性能的屬性, 而且依靠 position:relative 不知道會不會出現(xiàn)無法覆蓋的問題
實(shí)現(xiàn)三 利用 html2canvas 將目標(biāo)內(nèi)容繪制的一個(gè)底色半透明的 canvas 里面
具體步驟:
核心代碼:
let target = document.querySelector('.mid-center') let pos = target.getBoundingClientRect() let w = ~~pos.width let h = ~~pos.heightlet canvas = document.querySelector('#canvas') canvas.width = document.documentElement.clientWidth canvas.height = document.documentElement.clientHeight let ctx = canvas.getContext("2d"); canvas.style.display = 'block'html2canvas(target, {width: w,height: h, }).then( (cvs) => {ctx.drawImage(cvs, pos.left, pos.top) }) 復(fù)制代碼需要注意的是 這里 canvas.width 和 canvas.height 要手動設(shè)置,否則默認(rèn)是 300 * 150,這樣如果在樣式里設(shè)置寬高的話,會導(dǎo)致畫布被拉伸.
優(yōu)缺點(diǎn)
優(yōu)點(diǎn): 性能應(yīng)該相對會比較好一點(diǎn)(如果html2canvas性能內(nèi)有太差的話), 用 canvas 實(shí)現(xiàn), 也比較不容易碰到各種層級遮擋或顯示不全的問題.
缺點(diǎn): 實(shí)現(xiàn)方式相對繁瑣一點(diǎn),而且需要借助外部工具
實(shí)現(xiàn)四 把其他元素都設(shè)成半透明的.然后給 body 加一個(gè)黑色的底色
具體步驟:
核心代碼:
function showGuidance() {let main = document.querySelector('.main')main.className += ' darkBackGround'setOpticity(main) }function setOpticity (element) {let doms = Array.from(element.children) || []let hasMatched = falsefor (let el of doms) {if (!el.className.match(/mid-center/i) && el.children.length) {hasMatched = setOpticity(el)if (!hasMatched) el.className += ' halfTransparent'} else if(el.className.match(/mid-center/i)) {hasMatched = true} else {el.className += ' halfTransparent'}} return hasMatched } 復(fù)制代碼如果不小心把目標(biāo)元素的父元素也設(shè)置成半透明的,那么就算目標(biāo)元素沒有設(shè)置半透明,也會變透明,因?yàn)楦冈乩锩娴乃袃?nèi)容,都會透明
優(yōu)缺點(diǎn)
優(yōu)點(diǎn): 感覺沒有優(yōu)點(diǎn)哈
缺點(diǎn): 批量操作 dom, dom 元素多的情況下,性能極差
最后
以上所有實(shí)現(xiàn)方式,均按最簡單的實(shí)現(xiàn)方式來,未考慮一些特殊情況(如:resize, 有動畫等) 附上 源碼
總結(jié)
以上是生活随笔為你收集整理的新手引导动画的4种实现方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tomcat 设置虚拟路径
- 下一篇: 东莞首办工业机器人成果交流会听众爆满