1. 程式人生 > >原生JS跑馬燈效果

原生JS跑馬燈效果

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>跑馬燈效果</title>
    <style type="text/css">
        * { margin: 0; padding: 0; font-family: "微軟雅黑"; font-size: 14px; }
        .box { width: 1000px; height: 20px; margin: 50px auto; padding: 0 5px; background
: lightgreen; border: 1px dashed #0605CC; white-space: nowrap; overflow: hidden; } .box div { display: inline-block; height: 20px; color: #000; line-height: 20px; } .box div span { font-weight: bold; color: red; } </style> </head> <body> <div class="box" id="box"> <div
class="con" id="con"> <span>唐寅:</span>桃花塢裡桃花庵,桃花庵下桃花仙。桃花仙人種桃樹,又摘桃花換酒錢。酒醒只在花前坐,酒醉還來花下眠。半醉半醒日復日,花落花開年復年。但願老死花酒間,不願鞠躬車馬前。車塵馬足顯者事,酒盞花枝隱士緣。 </div> <div class="txt" id="txt"> <span>唐寅:</span>桃花塢裡桃花庵,桃花庵下桃花仙。桃花仙人種桃樹,又摘桃花換酒錢。酒醒只在花前坐,酒醉還來花下眠。半醉半醒日復日,花落花開年復年。但願老死花酒間,不願鞠躬車馬前。車塵馬足顯者事,酒盞花枝隱士緣。
</div> </div> <script type="text/javascript"> ~function () {//加一個自執行函式是為了讓函式形成閉包,防止函式內的變數影響全域性變數 var box = document.getElementById("box"); var con = document.getElementById("con"); var conWidth = parseFloat(window.getComputedStyle(con, null).width); function move() { box.scrollLeft++; if (box.scrollLeft >= conWidth) { box.scrollLeft = 0; } } var timer = window.setInterval(move, 10); box.onmouseover = function () { window.clearInterval(timer); }; box.onmouseout = function () { timer = window.setInterval(move, 10); }; }(); </script> </body> </html>