JavaScript/jQuery {Article011}

説明文の表示 ライブデモを見る▶
ようこそ「JavaScript/jQuery」へ...

CSSとJavaScript/jQueryでカスタマイズできるアナログ時計をつくる

ここでは、CSSとJavaScript/jQueryを使用して簡単にカスタマイズできるアナログ時計を作成する方法を解説します。 ここで使用するJavaScriptはanalogClockJsで公開されているアナログ時計をカスタマイズしています。 HTMLとCSSでアナログ時計を作成する詳しい説明は「Article012」を参照してください。 デジタル時計に興味のある方は「Article016」で解説しています。

作成手順

  1. VS2019(Visual Studio 2019 or Visual Studio 2022)を起動したら新規のWebフォーム「Article011.aspx」を作成します。

  2. Webフォームのヘッダータグ内「<head>...</head>」にSCRIPTタグを追加してjQueryの最新のライブラリーを取り込みます。 ここではjQuery 3.6.0のライブラリーを取り込んでいます。 次にここから、 「analogClockJs」をダウンロードして解凍します。そしてSCRIPTタグを追加してanalogClockのライブラリー「analogClock.js」を取り込みます。 さらにSCRIPTタグを追加したら、次のようなJavaScript/jQueryのコードを入力します。
    
    Article011.aspx:
    
    <script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
    <script src="js/Article011/analogClock.js"></script>
    <script type="text/javascript">
        // jQuery Document Ready Event...
        $(function () {
    
            $('#btnClock1').click(function () {
                var clock = $('div#clock1');
                if ($(clock).text().length == 0) {
                    AnalogClock("clock1");   
                }
                else {
                    $(clock).empty();
                }
            });
    
            $('#btnClock2').click(function () {
                var clock = $('div#clock2');
                if ($(clock).text().length == 0) {
                    AnalogClock("clock2", { width: 300, bgColor: "aquamarine" }); 
                }
                else {
                    $(clock).empty();
                }
            });
    
            $('#btnClock3').click(function () {
                var clock = $('div#clock3');
                if ($(clock).text().length == 0) {
                    AnalogClock("clock3", new AnalogClockOption(200, "#eee", "#333"));   
                }
                else {
                    $(clock).empty();
                }
            });
    
            $('#btnClock4').click(function () {
                var clock = $('div#clock4');
                if ($(clock).text().length == 0) {
                    var opt = new AnalogClockOption(); opt.width = 100; 
                    var clock4 = new AnalogClock("clock4", opt);
                    clock4.panel.style.border = "solid 1px red";
                }
                else {
                    $(clock).empty();
                }
            });
    
            $('#btnClock5').click(function () {
                AnalogClock5();
            });
    
            $('#selWidth').on('change', function () {
                AnalogClock5();
            });
    
            $('#selforeColor').on('change', function () {
                AnalogClock5();
            });
    
            $('#selbgColor').on('change', function () {
                AnalogClock5();
            });
    
            $('#selBorder').on('change', function () {
                AnalogClock5();
            });
    
            function AnalogClock5() {
                var clock = $('div#clock5');
                $(clock).empty();
                var opt = new AnalogClockOption();
                opt.width = $('#selWidth option:selected').val();
                opt.foreColor = $('#selforeColor option:selected').val();
                opt.bgColor = $('#selbgColor option:selected').val();
                var clock5 = new AnalogClock("clock5", opt);
                clock5.panel.style.border = $('#selBorder option:selected').val();
            }
        });
    </script>
    
    
    analogClock.js:
    
    /*
    An analogClock js plug that written by native javascript (jQuery is not required but also campatiable).
    Writtern by kenlam0083
    Base on MIT License
    
    Modified by Akio Kasai 2021/06/27
    */
    
    // AnalogClockOption Function  
    // Input: width, foreColor, bgColor
    function AnalogClockOption(width, foreColor, bgColor) {
        this.foreColor = foreColor ? foreColor : "#000";    
        this.bgColor = bgColor ? bgColor : "#eee";
        this.width = width ? width : 400;
    }
    
    // AnalogClock Main Function
    // Input: id, option
    function AnalogClock(id, option) {
    
        // padZero Function 1 ▶ 01
        var padZero = function(num) {
            if (num < 10) {
                num = '0' + num;
            }
            else {
                num = num.toString();
            }
            return num;
        }
    
        // DateTime Format Function() datetime ▶ yyyy/mm/dd hh:mm:ss
        var dateTimeFormat = function (time) {
            var str = "";
            str += time.getYear() + (time.getYear() > 1900 ? 0 : 1900) + "-";   
            str += padZero(time.getMonth() + 1) + "-";   
            str += padZero(time.getDate()) + "<br/>";
            str += padZero(time.getHours()) + ":";
            str += padZero(time.getMinutes()) + ":";
            str += padZero(time.getSeconds());
            return str;
        }
    
        if (!option) {
            option = {};    // avoid undefined exception
        }
    
        this.foreColor = option.foreColor ? option.foreColor : "#000";  // text color
        this.bgColor = option.bgColor ? option.bgColor : "#eee";
        this.width = option.width ? option.width : 400;
    
        this.container = document.getElementById(id);   // ★   
    
        if (!this.container) {
            return;
        }
    
        this.container.style.fontcolor = this.foreColor;
    
        // the static part
        // the outer panel of the clock, including the background
        // border-radius:50%;background-color:#eee;border:solid 1px #ccc;width:400px;height:400px;position:relative;
        this.panel = document.createElement("div"); // ★ 
    
        this.panel.style.borderRadius = "50%";
        this.panel.style.backgroundColor = this.bgColor;
        this.panel.style.border = "solid 1px #ccc";
        this.panel.style.width = this.width + "px";
        this.panel.style.height = this.width + "px";
        this.panel.style.position = "relative";
        this.container.appendChild(this.panel);
    
        // the digital clock on the panel
        // width:80%;line-height:40px;text-align:center;margin-top:250px;color:#333;
        var label = document.createElement("h4");   // ★    
    
        label.style.width = "100%";
        label.style.textAlign = "center";
        label.style.fontWeight = "normal";
        label.style.fontSize = this.width / 15 + "px";
        label.style.marginTop = this.width * 0.6 + "px";
        label.style.color = this.foreColor;
        label.innerHTML = dateTimeFormat(new Date());
    
        // hide if the width is not enough to show the digital clock
        if (this.width >= 100) {
            this.panel.appendChild(label);
        }
    
        // the container of hour numbers on the panel
        // padding:0;margin:0;list-style:none;position:absolute;left:180px;    
        var ul = document.createElement("ul");  // ★           
    
        ul.style.height = "100%";
        ul.style.padding = "0";
        ul.style.margin = "0";
        ul.style.listStyle = "none";
        ul.style.position = "absolute";
        ul.style.width = 40 + "px";
        ul.style.top = 0;
        ul.style.left = this.width / 2 - 20 + "px";
        ul.style.color = this.foreColor;
    
        this.panel.appendChild(ul);
    
        // the list of hour numbers on the panel
        for (var i = 0; i <= 5; i++) {
    
            //if html5 not supported
            if (!localStorage) {
                break;
            }
    
            // create li element
            // padding:0;margin:0; position: absolute; text-align:center;width:40px;height:400px;font-size:40px; 
            var list = document.createElement("li");
    
            list.style.padding = "0";
            list.style.margin = "0";
            list.style.position = "absolute";
            list.style.textAlign = "center";
            list.style.width = "40px";
            list.style.height = this.width + "px";
            list.style.fontSize = this.width / 10 + "px";
            ul.appendChild(list);
    
            list.style.transform = "rotate(" + 360 / 12 * (i + 1) + "deg)";
    
            // a pair of numbers, such as  1 and 7, 3 and 9, etc.
            // width:100%;position:absolute;text-align:center;
            var numTop = document.createElement("div");
            numTop.style.width = "100%";
            numTop.style.position = "absolute";
            numTop.style.textAlign = "center";
            numTop.innerHTML = i + 1;
    
            if (this.width < 100) {
                numTop.innerHTML = "●";
            }
    
            list.appendChild(numTop);
    
            numTop.style.transform = "rotate(" + -360 / 12 * (i + 1) + "deg)";  // recover the rotation
    
            // width:100%;position:absolute;text-align:center;
            var numBottom = document.createElement("div");
    
            numBottom.style.width = "100%";
            numBottom.style.position = "absolute";
            numBottom.style.textAlign = "center";
            numBottom.style.bottom = "0";
            numBottom.innerHTML = i + 7;
    
            if (this.width < 100) {
                numBottom.innerHTML = "●";
            }
    
            list.appendChild(numBottom);
    
            numBottom.style.transform = "rotate(" + -360 / 12 * (i + 1) + "deg)";   // recover the rotation
        }
    
        // hour hand
        // width:8px;height:8px;left:196px;top:96px;border-top:solid 100px #ff6a00; border-bottom-width:100px;  
        var hourWidth = this.width * 0.02;
        var hour = document.createElement("div");
    
        var hourTop = this.width * 0.25 - (hourWidth * 0.5);
        var hourleft = this.width * 0.5 - hourWidth * 0.5;
        hour.style.width = hourWidth + "px";
        hour.style.height = hourWidth + "px";
        hour.style.position = "absolute";
        hour.style.border = "solid 0px transparent";
        hour.style.left = hourleft + "px";
        hour.style.top = hourTop + "px";
        hour.style.borderTop = "solid " + (this.width * 0.5 - hourTop) + "px #f60";
        hour.style.borderBottomWidth = (this.width * 0.5 - hourTop) + "px";
    
        // only visible in HTML5 supported browser
        if (localStorage) {
            this.panel.appendChild(hour);
        }
    
        // minute hand
        // width:4px;height:4px;left:198px;top:48px;border-top:solid 150px #0094ff; border-bottom-width:150px;
        var min = document.createElement("div");
    
        var minWidth = this.width * 0.01;
        var minTop = this.width * 0.1 - (minWidth * 0.5);
        var minleft = this.width * 0.5 - minWidth * 0.5;
        min.style.width = minWidth + "px";
        min.style.height = minWidth + "px";
        min.style.position = "absolute";
        min.style.border = "solid 0px transparent";
        min.style.left = minleft + "px";
        min.style.top = minTop + "px";
        min.style.borderTop = "solid " + (this.width * 0.5 - minTop) + "px #09f";
        min.style.borderBottomWidth = (this.width * 0.5 - minTop) + "px";
    
        if (localStorage) {
            this.panel.appendChild(min);
        }
    
        // second hand
        // width:1px;height:1px;position:absolute;border:solid 0px transparent;left:199px;top:19px;border-top:solid 180px #333; border-bottom-width:180px;  
        var sec = document.createElement("div");
        var secWidth = 1;
        var secTop = this.width * 0.05;
        sec.style.width = secWidth + "px";
        sec.style.height = secWidth + "px";
        sec.style.position = "absolute";
        sec.style.border = "solid 0px transparent";
        sec.style.left = (this.width * 0.5 - secWidth) + "px";
        sec.style.top = secTop + "px";
        sec.style.borderTop = "solid " + (this.width * 0.5 - secTop) + "px " + this.foreColor;
        sec.style.borderBottomWidth = (this.width * 0.5 - secTop) + "px";
    
        if (localStorage) {
            this.panel.appendChild(sec);
        }
    
        // the center point
        // content:"";background-color:#333;width:10px;height:10px;position:absolute;left:195px;top:195px;border-radius:50%; 
        var point = document.createElement("div");
    
        var pointWidth = this.width * 0.05;
        point.style.width = pointWidth + "px";
        point.style.height = pointWidth + "px";
        point.style.position = "absolute";
        point.style.backgroundColor = this.foreColor;
        point.style.left = this.width * 0.5 - (pointWidth * 0.5) + "px";
        point.style.top = this.width * 0.5 - (pointWidth * 0.5) + "px";
        point.style.borderRadius = "50%";
    
        if (localStorage) {
            this.panel.appendChild(point);
        }
    
        // start the clock (the animation part)
        this.loop = setInterval(function () {
            var now = new Date();
            label.innerHTML = dateTimeFormat(now);
    
            var roS = 1.0 * 360 / 60 * now.getSeconds();
            var roM = 1.0 * 360 / 60 * now.getMinutes();
            var roH = 1.0 * 360 / 12 * (now.getHours() % 12) + 1.0 * 360 / 12 * (now.getMinutes() / 60);
    
            sec.style.transform = 'rotate(' + roS + 'deg)';
            min.style.transform = 'rotate(' + roM + 'deg)';
            hour.style.transform = 'rotate(' + roH + 'deg)';
        }, 1000);
    }
    
  3. Webフォームにアナログ時計を表示するために、HTMLのINPUT(type="button")、DIV、HRタグを追加します。 さらに、5番目のアナログ時計には時計の幅(Width)、前景色(foreColor)、背景色(bgColor)、ボーダー(border)をカスタマイズできるようにSELECTタグを追加します。
    
    Article011.aspx:
    
    <input id="btnClock1" type="button" value="Show/Hide Analog Clock #1" />
    <div id="clock1"></div>
    <hr />
    
    <input id="btnClock2" type="button" value="Show/Hide Analog Clock #2" />
    <div id="clock2"></div>
    <hr />
    
    <input id="btnClock3" type="button" value="Show/Hide Analog Clock #3" />
    <div id="clock3"></div>
    <hr />
    
    <input id="btnClock4" type="button" value="Show/Hide Analog Clock #4" />
    <div id="clock4"></div>
    <hr />
    
    <input id="btnClock5" type="button" value="Show/Change Analog Clock #5" />
    Width:
    <select id="selWidth">
        <option label="100px" value="100" />
        <option label="200px" value="200" />
        <option label="300px" value="300" selected />
        <option label="400px" value="400" />
        <option label="500px" value="500" />
    </select>
    
    foreColor:
    <select id="selforeColor">
        <option label="red" value="red" />
        <option label="white" value="white" selected />
        <option label="blue" value="blue" />
    
    </select>
    
    bgColor:
    <select id="selbgColor">
        <option label="darkcyan" value="darkcyan" />
        <option label="black" value="black" selected />
        <option label="gray" value="gray" />
    </select>
    
    border:
    <select id="selBorder">
        <option label="solid 5px red" value="solid 5px red" />
        <option label="double 5px red" value="double 5px red" selected />
        <option label="dotted 5px red" value="dotted 5px red" />
    </select>
    
    <div id="clock5"></div>    
    

操作手順

  1. Webページが表示されたら[Show/Hide Analog Clock #1-5]のボタンをクリックします。 このボタンはトグルボタンになっていますのでアナログ時計を表示・非表示します。

  2. 5番目のアナログ時計は、ドロップダウンリストから時計の「幅」「前景色」「背景色」「ボーダー」を選択してカスタマイズすることができます。

Live DEMO





Width: foreColor: bgColor: border: