DIV CSS 佈局教程網

JS 實現 Div 向上浮動:setInterval 與滑鼠懸停暫停
編輯:關於JavaScript     

做一個從畫面底部緩緩上浮的小浮動元素,核心只有兩件事:計時器反覆改 bottom,以及滑鼠移入時暫停、移出時恢復。

HTML 與 JS

<div id="newsOne"
     onmouseover="CleartTimeInterVal();"
     onmouseout="resetInterVal();"
     style="position: absolute; width: 100px;">
    <a href="https://www.jb51.net" target="_blank"></a>
</div>

<script type='text/javascript'>
var newsOne = document.getElementById("newsOne");
newsOne.style.bottom = 0;
newsOne.style.left = window.screen.availWidth - 100;

var bottom = 0;

function newsScroll() {
    if (bottom > (window.screen.availHeight - window.screenTop)) {
        bottom = 0;
        newsOne.style.bottom = 0;
    } else {
        bottom = bottom + 15;
        newsOne.style.bottom = bottom;
    }
}

var timeid = setInterval(newsScroll, 300);

function CleartTimeInterVal() {
    clearInterval(timeid);
}

function resetInterVal() {
    timeid = setInterval(newsScroll, 300);
}
</script>

運作說明

每 300 毫秒把 bottom 增加 15 像素,到達視窗高度時歸零重來,形成循環上浮。滑鼠移入清除計時器讓它停住,移出後重新啟動。

可改進的地方

  • window.screen 取得的是螢幕尺寸,而非瀏覽器視窗;若希望元素相對視窗定位,改用 document.documentElement.clientWidth 與 clientHeight,並搭配 position: fixed 會更準確。
  • 每次重設 15 像素顯得跳動,可改為 requestAnimationFrame 搭配 CSS transition,或直接用 CSS @keyframes 動畫,效能與平順度都更好。
  • 計時器需在頁面卸載時清除,避免不必要的背景運算。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved