javascript类编初步 一

内容纲要

     javascript类编初步 一


Javascript是一门面向对象的强类型预编译的编程语言,是Ecmascript的一种现代常用实现。

这里我们编写一系列组件来熟悉现代版本的javascript。

一、短信发送类按钮

A. 结构目录

SendButton
 +-- src
 |    -- main.ts
 +-- index.html
 +-- app.scss
 +-- tsconfig.json

B. 页面布局

1) 在页面中手动加入容器,并配置id:

index.html

<div id="content"></div>

2) 设置css样式:
app.scss

html,body{
    width: 100%;
    height: 100%;
}
body {
    font-family: 'Segoe UI', sans-serif;
}
#content{
    position: absolute;
    top:50%;
    left:50%;
    width: 500px;
    height: 60px;
    transform: translateY(-50%);
    transform: translateX(-50%);
}

span {
    font-style: italic;
}

button,input{
    width: 200px;
    height: 50px;
    position: relative;
    font-size: 30px;
    padding-left:5px;
    /*transform: translateY(-50%);
    transform: translateX(-50%);*/
}

3) 这里什么功能都没有,只是为了好看

C. 框架构造

1) 编写一个SendButton类:

class SendButton{

    constructor(){
        console.log('init.');
    }
    start(){
    }
    stop(){
    }
}

并在SendButton类中添加start()stop()两个方法。

2) 声明所需变量:
SendButton类中声明所需全局变量:

private element:HTMLElement;
private button:HTMLElement;
private input:HTMLElement;
private ele:HTMLElement;
private timer:number;
private step:number = 10;

3) 在构造函数中初始化所需变量,给按钮增加事件侦听:

let self = this;
this.element = element;
this.input = document.createElement('input');
this.input.innerHTML = 'ceshi.';
this.button = document.createElement('button');
this.button.innerHTML = 'send';
this.element.appendChild(this.input);
this.element.appendChild(this.button);
this.button.addEventListener('click',(e) =>{
    self.start();
});

并给构造函数增加参数:

constructor(element:HTMLElement){
}

4) 添加定时器:

start(){
    this.button.disabled = true;
    this.button.innerHTML = this.step + 's';
    this.timer = setInterval(()=>{
        this.step = this.step - 1;
        this.button.innerHTML = this.step + 's';
        if(this.step <= 0) this.stop();
    },1000);
 }

5) 停止定时器:

stop(){
    clearInterval(this.timer);
    this.button.disabled = false;
    this.button.innerHTML = 'send';
    this.step = 10;
}

6) 在加载完成后实例化SendButton:

window.addEventListener('load',e =>{
    let container = document.getElementById('content');
    let gretter = new Greeter(container);
});

7) 运行项目:
可以使用命令或者点击运行和快捷键构建项目。

注意
由于Javascript需要先编译再运行,建议在运行前先清理项目,再构建,编译,后运行(自动构建出现异常时同样操作)。

code enjoy! 🤩

作者:indeex

链接:http://indeex.cc

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


发表评论

您的电子邮箱地址不会被公开。