1. 程式人生 > >JavaScript-06-Dom操作

JavaScript-06-Dom操作

1.上下切換圖片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上下切換圖片</title>
</head>
<body>
<img name="icon" src="image/icon_01.png"
> <p></p> <button>上一張</button> <button>下一張</button> <script> // 1.全域性的變數 var maxIndex = 9; var minIndex = 1; var currentIndex = minIndex; // 2.拿到要操作的標籤 var img = document.getElementsByName('icon')[0]; var pre = document.getElementsByTagName(
'button')[0]; var next = document.getElementsByTagName('button')[1]; // 3.監聽按鈕的點選 // 3.1 上一張 pre.onclick = function () { if (currentIndex == minIndex){ // 邊界處理 currentIndex = maxIndex; }else{ // 正常情況 currentIndex -=1; } // 改變src img.src
= 'image/icon_0' + currentIndex + '.png'; console.log(img.src); }; // 3.2 下一張 next.onclick = function () { if (currentIndex == maxIndex) { currentIndex = minIndex; }else { currentIndex +=1; } // 改變src img.src = 'image/icon_0' + currentIndex + '.png'; console.log(img.src); } </script> </body> </html>

2.定時器操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>定時器</title>
    <style>
        body{
            background-color: black;
            text-align: center;
            margin-top: 100px;
        }
        div{
            color: red;
            font-size: 150px;
        }
        img{
            display: none;
        }

        p{
            display: none;
            color: red;
            font-size: 100px;
        }
    </style>
</head>
<body>
    <img id="icon" src="./image/flower.gif" alt="">
    <p id="word">我對你的愛滔滔不絕..</p>
    <div id="number">4</div>
    <script type="text/javascript" >
        //1.拿到要操作的標籤
        var img = document.getElementById('icon');
        var word = document.getElementById('word');
        var number = document.getElementById('number');
        //2.設定定時器
        var timer = setInterval(function () {
            //改變倒計時數字
            number.innerText -=1;
            //判斷
            if (number.innerText == 0){
                // 清除定時器
                clearInterval(this.timer);
                //顯示
                word.style.display = 'block';
                img.style.display = 'inline-block';
                //隱藏number
                number.style.display = 'none';

            }

        },1000)
    </script>
</body>
</html>