做一個從畫面底部緩緩上浮的小浮動元素,核心只有兩件事:計時器反覆改 bottom,以及滑鼠移入時暫停、移出時恢復。
<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 會更準確。requestAnimationFrame 搭配 CSS transition,或直接用 CSS @keyframes 動畫,效能與平順度都更好。