美文网首页我爱编程
TypeScript——实战1

TypeScript——实战1

作者: _____西班木有蛀牙 | 来源:发表于2018-05-24 01:02 被阅读43次
Timer.ts文件
module Time {
    export class Test {
        element: HTMLElement;
        span: HTMLElement;
        timer: number;

        constructor (e:HTMLElement) {
            this.element = e;
            this.element.innerHTML = '现在的时间是:';
            this.span = document.createElement('span');
            this.element.appendChild(this.span);
            this.span.innerHTML = new Date().toTimeString();
        }

        start() {
            this.timer = setInterval(() => this.span.innerHTML = new Date().toTimeString());
        }

        end() {
            clearInterval(this.timer);
        }
    }
}
JSTimer.js文件
var div = document.createElement("div");
document.body.appendChild(div);
var obj = new Time.Test(div);
// 创建开始按钮,并绑定事件
var start_button = document.createElement('button');
start_button.innerHTML = 'start';
start_button.onclick = function () {
    obj.start();
}
document.body.appendChild(start_button);

// 创建停止按钮,并绑定事件
var stop_button = document.createElement('button');
stop_button.innerHTML = 'stop';
stop_button.onclick = function () {
    obj.stop();
}
document.body.appendChild(stop_button);

time.html文件
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="Timer.js"></script>
    <script src="JSTimer.js"></script>
</body>
</html>

注意:编写的是 Timer.ts 引入的是编译之后的 Timer.js

直接运行我们可以看到

图1
点击 start 按钮 每个 500毫秒 更新一次时间,点击 stop 按钮 停止更新时间

相关文章

网友评论

    本文标题:TypeScript——实战1

    本文链接:https://www.haomeiwen.com/subject/wlcjjftx.html