【前端学习】Day-18 js定时器、事件绑定、案例


前端三大技术:HTML、CSS、JS(原生JS、JQuery、Vue)

  • DOM - 节点(标签)操作(增删改查) — D -> Document
  • BOM - 打开窗口、滚动窗口、定时事件 B -> Browser

1. js定时器

js中的定时器有两种:Interval、Timeout

  1. Interval定时器的开启和关闭
    setInterval(函数, 时间) - 创建定时器对象,每隔指定时间就自动调用指定函数
  2. Timeout定时器(定时炸弹,不常用)
<!DOCTYPE HTML>
<!-- 
前端三大技术:HTML、CSS、JS(原生JS、JQuery、Vue)
DOM - 节点(标签)操作(增删改查) --- D -> Document
BOM - 打开窗口、滚动窗口、定时事件  B -> Browser
 -->
<html lang="zh_CN">

<head>
    <meta charset="UTF-8">
    <title>标题</title>
</head>
    
<body>
    <div id="box" style="background-color: red; width: 50px; height: 50px; position: absolute; top: 10px;"></div>
    <button type="button" onclick="clearInterval(t1)">关闭定时器1</button>
</body>
    
</html>

<script>
    // js中的定时器有两种:Interval、Timeout
    // 1) Interval定时器的开启和关闭
    // setInterval(函数, 时间) - 创建定时器对象,每隔指定时间就自动调用指定函数

    // 定时打印Hellow World!
    num = 1
    t1 = setInterval(function(){
        console.log('Hellow World!' + num)
        num++
    }, 1000)

    // 让方块从上往下移动
    top1 = 0
    top2 = 200
    setInterval(function(){
        if (top1 <= 200){
            top1 += 0.1
            document.getElementById('box').style.top = top1 + 'px'
            // console.log(top1)
        }
        else{while(top1 >= 0){
                top1 -= 0.1
                document.getElementById('box').style.top = top1 + 'px'
            }
        }
    }, 1)

    // 停止定时器
    // clearInterval(定时器对象)
    clearInterval(t1)

    // 2) Timeout定时器(定时炸弹)
    t3 = setTimeout(function(){console.log('Hellow')}, 1000)
    clearTimeout(t3)
</script>

案例
定时跳转百度页面

<!DOCTYPE HTML>
<html lang="zh_CN">

<head>
    <meta charset="UTF-8">
    <title>标题</title>
</head>

<body>
    <a id="baidu" href="https://www.baidu.com"></a>
</body>

</html>

<script>
    num = 11
    t1 = setInterval(function () {
        num -= 1
        console.log(num)

        if (num < 0) {
            clearInterval(t1)
            window.location = 'https://www.baidu.com'
            // window.open('https://www.baidu.com')
        } else {
            document.getElementById('baidu').innerText = num + '秒后自动跳转百度页面...'
        }
    }, 1000)
</script>

2. 事件绑定

事件绑定 - 让网页内容和对人类的指定行为作出反应

  1. 事件三要素:事件源、事件、事件驱动程序

  2. 绑定事件的方法

    1. 在标签内部给事件源的事件属性赋值: <标签名 οnclick=“事件驱动程序”></标签名>
      函数中的this是window对象
    2. 在js中给标签对应的节点的事件属性值赋值:事件源节点.onclick = 事件驱动程序对应的函数
      注意:事件驱动程序对应的函数必须是普通函数名或者是匿名函数
      函数中的this是事件源
    3. 在js中通过节点对象的.addEventListener绑定事件:事件源节点.addEventListener(事件名称, 事件驱动程序对应的函数)
      注意:这儿的事件名需要把on去掉
  3. 常见的事件

    1. 鼠标相关事件:(任何可见标签都可以绑定鼠标事件)
      onclick - 鼠标点击事件
      onmouseover - 鼠标悬停在标签上
      onmouseout - 鼠标从标签上离开

    2. 按键事件
      onkeypress - 按某个按键对应事件
      onkeydown - 某个按键按下对应事件
      onkeyup - 某个按键按下后弹起来对应的事件
      注意:按键相关事件在绑定的时候必须通过js绑定(方法2、方法3),才可以在函数中添加事件对应的参数,来获取按键信息

    3. 值变事件 - 用于检测下拉列表的选项发生改变的时候
      onchange

事件绑定

<!DOCTYPE HTML>
<html lang="zh_CN">

<head>
    <meta charset="UTF-8">
    <title>标题</title>
</head>

<body>
    <button type="button" onclick="alert('你好吗?')">问候1</button>
    <button type="button" onclick="func1()">问候2</button>
    <br><br>
    <button id="add" type="button" onclick="add()">+</button>
    <span id="number">0</span>
    <button id="sub" type="button" onclick="sub()">-</button>
    <br><br>
    <!-- <div id="add" type="button" οnclick="add()" style="width: 50px;height: 50px; background-color: aqua; text-align: center;line-height: 50px;">+</div>
    <div id="number" type="text" style="width: 50px;height: 50px; background-color: greenyellow; text-align: center;line-height: 50px;">0</div>
    <div id="sub" type="button" οnclick="sub()" style="width: 50px;height: 50px; background-color: aqua; text-align: center;line-height: 50px;">-</div>
    <br> -->
    <button id="btn1" onclick="func2()">问候1</button>
    <button id="btn2">问候2</button>
    <button id="btn3">确认</button>
    <br>
    <hr>
    <button id="btn_1" type="button" onclick="func4()">删除1</button>
    <button id="btn_2" type="button" onclick="func5()">删除2</button>
    <button id="btn_3" type="button" onclick="func6()">删除3</button>
    <button id="btn_4" type="button" onclick="func7()">删除4</button>
    <br>
    <hr>
    <button class="del" type="button">删除1</button>
    <button class="del" type="button">删除2</button>
    <button class="del" type="button">删除3</button>
    <button class="del" type="button">删除4</button>
</body>

</html>

<script>
    function func1() {
        alert('你好!')
    }

    num = 0
    function add() {
        num += 1
        document.getElementById('number').innerText = num
    }
    function sub() {
        num -= 1
        document.getElementById('number').innerText = num
    }

    // 绑定方式1
    function func2() {
        alert('你好?')
        console.log(this)
    }
    // 绑定方式2
    document.getElementById('btn2').onclick = function func3() {
        alert('你今年多大了?')
        console.log(this)
    }

    // ====================删除节点====================
    // 删除节点-1
    function func4() {
        document.getElementById('btn_1').remove()
    }
    function func5() {
        document.getElementById('btn_2').remove()
    }
    function func6() {
        document.getElementById('btn_3').remove()
    }
    function func7() {
        document.getElementById('btn_4').remove()
    }
    // 删除节点-2
    function delAction() {
        this.remove()
    }

    btns = document.getElementsByClassName('del')
    for (index = 0; index < 4; index++) {
        btns[index].onclick = delAction
    }

    document.getElementById('btn3').addEventListener('click', function(){
        confirm('是否删除?')
    })   // 去掉on

</script>

常见事件类型

<!DOCTYPE HTML>
<html lang="zh_CN">
    
<head>
    <meta charset="UTF-8">
    <title>标题</title>
</head>
    
<body>
    <button type="button" onmouseover="alert('鼠标悬停')">按钮</button>
    <hr>
    <button id="btn2" type="button" onmouseover="func_over()" onmouseleave="func_leave()">点我呀~</button>
    <hr>
    <button id="btn3" type="button" onmouseover="func_run()" onmouseleave="func_leave()" style="left:10px;">点我呀~</button>
    <hr>
    <input id="input1" onkeypress="keyPress()">
    <hr>
    <select name="city" id="city">
        <option value="成都">成都</option>
        <option value="重庆">重庆</option>
        <option value="北京">北京</option>
        <option value="上海">上海</option>
    </select>
</body>
    
</html>

<script>
    // ===================鼠标相关事件===================
    function func_over(){
        document.getElementById('btn2').innerText = '点不了,气不气?'

    }
    function func_leave(){
        document.getElementById('btn2').innerText = '点我呀~'
    }
    function func_run(){
        b3 = document.getElementById('btn3')
        // b3 = document.getElementsByTagName('button')
        b3.style.left = '500px'
    }

    // ===================键盘相关事件===================
    input = document.getElementById('input1')
    input1.onkeypress = function (evt){
        console.log('按键按下!', evt, evt.key)
    }

    // 
    document.getElementById('city').onchange = function (){
        console.log('选项发生改变!', city.value)
    }

</script>

3. 案例

动态添加和删除、缩略图

<!DOCTYPE HTML>
<html lang="zh_CN">

<head>
    <meta charset="UTF-8">
    <title>标题</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        #box1 {
            margin-left: 50px;
            margin-top: 20px;
        }
        #box1 > div{
            background-color: #629ea0;
            width: 200px;
            height: 50px;
            margin-top: 2px;
            color: white;
            font-size: 20px;
            line-height: 50px;
        }
        #box1 P{
            float: left;
            text-align: center;
            width: 180px;
        }
        #box2{
                margin-top: 20px;
                margin-left: 50px;
            }
        #box2>input{
            border: 0;
            border-bottom: 1px solid rgb(169,169,169);
            width: 200px;
            height: 50px;
            outline: 0;
            text-align: center;
            font-size: 20px;
            vertical-align: bottom;		/*垂直对齐方式*/
        }
        #box2>button{
            width: 70px;
            height: 28px;
            color: white;
            font-size: 18px;
            border: 0;
            background-color: rgb(253,123,87);
        }
    </style>
</head>

<body>
    <div>
        <img id="img" src="../file/img/picture-1.jpg">
    </div>
    <div>
        <img id="img1" class="im" src="../file/img/thumb-1.jpg">
        <img id="img2" class="im" src="../file/img/thumb-2.jpg">
        <img id="img3" class="im" src="../file/img/thumb-3.jpg">
    </div>
    <hr>
    <div id="box1">
        <div>
            <p>苹果</p><span>x</span>
        </div>
        <div>
            <p>香蕉</p><span>x</span>
        </div>
        <div>
            <p>火龙果</p><span>x</span>
        </div>
        <div>
            <p>西瓜</p><span>x</span>
        </div>
    </div>
    <div id="box2">
        <input type="">
        <button type="button" onclick="add_friut">确定</button>
    </div>
    <script type="text/javascript">
        function add_friut(){
            //1.获取输入框内容
            input1 = document.getElementById('name')
            name = input1.value
            input1.value = ''
            
            //2.创建新水果对应的新标签
            div = document.createElement('div')
            p = document.createElement('p')
            p.innerText = name
            span = document.createElement('span')
            span.innerText = '×'
            div.appendChild(p)
            div.appendChild(span)
            // 新增的水果的颜色是随机色
            // random()  -  产生0~1的随机数
            r = parseInt(Math.random()*255)
            g = parseInt(Math.random()*255)
            b = parseInt(Math.random()*255)
            div.style.backgroundColor = "rgba("+r+","+g+","+b+",0.3)"
            
            box1 = document.getElementById('box1')
            box1.insertBefore(div, box1.firstElementChild)
        }
    </script>
</body>

</html>

<script type="text/javascript">
    // document.getElementById('img1').onmouseover = function () {
    //     document.getElementById('img').src = '../file/img/picture-1.jpg'
    // }
    // document.getElementById('img2').onmouseover = function () {
    //     document.getElementById('img').src = '../file/img/picture-2.jpg'
    // }
    // document.getElementById('img3').onmouseover = function () {
    //     document.getElementById('img').src = '../file/img/picture-3.jpg'
    // }

    function change() {
        document.getElementById('img').src = '../file/img/picture-' + this.i + '.jpg'
    }
    img_ch = document.getElementsByClassName('im')
    for (index = 0; index < 4; index++) {
        a = img_ch[index]
        a.i = index + 1
        img_ch[index].onmouseover = change
    }
    
</script>

流氓广告

<!DOCTYPE HTML>
<html lang="zh_CN">

<head>
    <meta charset="UTF-8">
    <title>标题</title>
    <style>
        #ad {
            width: 250px;
            height: 250px;
            float: right;
            background-color: blue;
        }

        #p {
            width: auto;
            margin-top: 0;
            color: rgb(255, 253, 56);
        }

        #clo {
            background-color: rgb(128, 128, 128);
            color: white;
            margin-top: 0;
            float: right;
        }

        #clo:hover {
            cursor: pointer;
        }
    </style>
</head>

<body>
    <div id="ad" style="margin-top: 0px;margin-right: 0px;">
        <span id="p">此广告位招租</span>
        <span id="clo" onclick="run()">关闭</span>
    </div>
</body>

</html>

<script>
    num = 0
    n = 2
    function run() {
        if (num < 50 * n) {
            num += 50
            document.getElementById('ad').style.marginTop = num + 'px'
            document.getElementById('ad').style.marginRight = num + 'px'
        } else {
            r = document.getElementById('ad')
            r.remove()
        }
    }
</script>

滑块闪烁

<!DOCTYPE HTML>
<html lang="zh_CN">

<head>
    <meta charset="UTF-8">
    <title>标题</title>
    <style>
        /* * {
            margin: 0;
            padding: 0;
        } */

        #box {
            width: 1000px;
            height: 500px;
            /* background-color: aquamarine; */
            border: 1px solid black;
            margin: auto;
        }
        #button {
            text-align: center;
            margin-top: 10px;
        }
        .btn {
            border: 0;
            background-color: red;
            color: white;
            width: 70px;
            height: 30px;
        }
        #box > div{
            width: 100px;
            height: 100px;
            float: left;
        }
    </style>
</head>

<body>
    <div id="box">

    </div>
    <div id="button">
        <button id="btn1" class="btn" type="button" onclick="add()">添加</button>
        <button id="btn2" class="btn" type="button" onclick="t1">闪烁</button>
    </div>
</body>

</html>

<script>
    // 随机颜色
    function color(a=1){
        r = parseInt(Math.random()*255)
        g = parseInt(Math.random()*255)
        b = parseInt(Math.random()*255)
        return `rgba(${r},${g},${b},${a})`
    }
    // 添加div
    count = 0
    function add() {
        var div = document.createElement('div')
        div.style.backgroundColor = color(1)
        div.class = 'box2'
        var box = document.getElementById('box')
        box.insertBefore(div,box.firstElementChild)
        count += 1
        if (count>50){
            box.lastElementChild.remove()
            count -= 1
        }

    }
    // 闪烁
    document.getElementById('btn2').onclick = function(){
        if (this.innerText == '闪烁'){
            this.innerText = '暂停'
            t1 = setInterval(function(){
                var box2 = document.getElementById('box').children
                for (i=0;i<box2.length;i++){
                    box2[i].style.backgroundColor = color(1)
                }
            }, 100)
        }else{
            this.innerText = '闪烁'
            clearInterval(t1)
        }
    }


</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值