Solve the problem of style in cannot read property ‘style’ of null

 

<script type="text/javascript">
        function updateTime(){
            var timeNow = new Date();
            var hour = timeNow.getHours();
            var minute = timeNow.getMinutes();
            var second = timeNow.getSeconds();
            var millisecond= timeNow.getMilliseconds();

            // Get the hands on the dial to rotate
            var sec = document.getElementById('seconds');
            var min = document.getElementById("minutes");
            var h = document.getElementById("hours");
            sec.style.transform = 'rotateZ(' +(second*360/60 + millisecond * 6/1000)+ 'deg)';
            min.style.transform = 'rotateZ(' + (minute*360/60) + 'deg)';
            h.style.transform = 'rotateZ(' + (hour*360/12 + minute*30/60) +'deg)';
        }
        setInterval(function () {
            updateTime();
        }, 50)
        updateTime();
        var scales = document.querySelectorAll('.scale');
        var nums = document.querySelectorAll('.num');
        for(var i = 0; i < scales.length;i++){
            scales[i].style.transform = 'rotateZ(' + (i*30)+ 'deg) translateY(-200px)';
            nums[i].style.transform = 'rotateZ(' + (i*-30)+ 'deg)';
        }
    </script>
    <div id="all">
        <div class="second" id="seconds"></div>
        <div class="minute" id="minutes"></div>
        <div class="hour" id="hours"></div>
        <div class="scale"><span class="num">12</span></div>
        <div class="scale"><span class="num">1</span></div>
        <div class="scale"><span class="num">2</span></div>
        <div class="scale"><span class="num">3</span></div>
        <div class="scale"><span class="num">4</span></div>
        <div class="scale"><span class="num">5</span></div>
        <div class="scale"><span class="num">6</span></div>
        <div class="scale"><span class="num">7</span></div>
        <div class="scale"><span class="num">8</span></div>
        <div class="scale"><span class="num">9</span></div>
        <div class="scale"><span class="num">10</span></div>
        <div class="scale"><span class="num">11</span></div>

    </div>

The problem is that the JS is written first and then the HTML code is written. Therefore, when the program is executing, the JS is compiled first. At this time, the HTML has not been parsed, so the style attribute cannot be parsed. The solution is to put the HTML file on it

Similar Posts: