1. 程式人生 > >JS實現文字的左右滾動

JS實現文字的左右滾動

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<style>
    p{position: absolute;left: 125px; top: 100px;}
</style>

<script>
    var tag = 0;//標誌,判斷物件當前位置是在最左還是最右,注意這裡必須設定為全域性變數,否則在執行setTimeOut方法會重置為0,使得無法再向右返回
    //移動文字
    function moveWord(){
        var resource = document.getElementById("word");
        var x = parseInt(window.getComputedStyle(resource,null).left);//獲取當前文字所在x軸位置,並轉換為int型別
        var tx = 500;//最右目標
        var rx = 125;//最左目標即起始位置
        if(x < tx && tag == 0)//向右滾動
        {
            x++;
            if(x == tx)//判斷到達最右目標後,標誌設定為1
                tag = 1;
        }
        if(x> rx && tag == 1)//向左滾動
        {
            x--;
            if(x == rx)//判斷到達最左目標後,標誌設定為0
                tag = 0;
        }
        resource.style.left = x + "px";//設定物件的x軸位置
        t = setTimeout("moveWord()",10);//執行更新,10代表移動的速度,值越大移動越慢

    }
    window.onload =moveWord;
</script>
<body>
<p id="word">左右滾動文字</p>
</body>
</html>

在獲取文字的x軸位置,上面寫的是內聯樣式,如果把樣式寫為內嵌樣式的話,可以寫成

var x = parseInt(resource.style.left);