您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“原生JS怎么實(shí)現(xiàn)分享側(cè)邊欄”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“原生JS怎么實(shí)現(xiàn)分享側(cè)邊欄”吧!
實(shí)現(xiàn)效果如下:
以下是代碼實(shí)現(xiàn),方便大家復(fù)制粘貼。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>分享到效果</title> <style> #share { position: fixed; width: 100px; height: 200px; background-color: lightblue; left: -100px; top: 100px; } #share span { width: 20px; height: 60px; line-height: 20px; text-align: center; left: 100px; top: 70px; position: absolute; background-color: yellow; } </style> </head> <body> <div id="share"> <span>分享到</span> </div> <script> // 獲取元素 var share = document.getElementById("share"); // 將事件設(shè)置給share share.onmouseover = function () { animate(this, "left", 0); }; share.onmouseout = function () { animate(this, "left", -100); }; // animate運(yùn)動(dòng)函數(shù) function animate(tag, attr, target) { clearInterval(tag.timer); tag.timer = setInterval(function () { // 獲取某個(gè)屬性的當(dāng)前狀態(tài) // 由于具有單位,需要取整 // parseInt("hehe") => NaN NaN || 0 // 為了應(yīng)對(duì)auto轉(zhuǎn)換為NaN的問(wèn)題,我們使用短路操作,保證程序的健壯性 var leader = parseInt(getStyle(tag, attr)) || 0; // 緩動(dòng)公式的一部分是更改step的值 var step = (target - leader) / 10; // 由offsetLeft在取值的時(shí)候會(huì)四舍五入,step如果比較小,會(huì)造成無(wú)法運(yùn)動(dòng)的問(wèn)題 // 根據(jù)步數(shù)的正負(fù),更改取整方式 step = step > 0 ? Math.ceil(step) : Math.floor(step); // 緩動(dòng)公式 leader = leader + step; // 設(shè)置給某一個(gè)屬性 tag.style[attr] = leader + "px"; // 檢測(cè)是否走到了指定位置 if (leader == target) { clearInterval(tag.timer); } }, 17); } // 用于獲取某個(gè)標(biāo)簽的某個(gè)樣式屬性值 // 帶單位 function getStyle(tag, attr) { // 檢測(cè)支持哪一個(gè) // box.currentStyle,如果不存在值為undefined // getComputedStyle如果瀏覽器不支持。相當(dāng)于變量未聲明,報(bào)錯(cuò) if (tag.currentStyle) { // ie支持 return tag.currentStyle[attr]; } else { // 標(biāo)準(zhǔn)方法 return getComputedStyle(tag, null)[attr]; } } </script> </body> </html>
到此,相信大家對(duì)“原生JS怎么實(shí)現(xiàn)分享側(cè)邊欄”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。