DOM之操作页面元素

DOM之操作页面元素

  在DOM之获取元素一文中,我们已经掌握了怎么去获取HTML中的页面元素,获取页面元素就是为了在某个动作下去修改它,例如登录按钮点击后会跳转到其他页面,鼠标经过某些区域时,会展现某些隐藏的内容,这些动作就是触发事件,先对 JS 中的事件做个了解吧~

一、事件基础

1.1 事件概述

  JavaScript 使我们有能力创建动态页面,而事件是可以被 JavaScript 侦测到的行为。例如鼠标经过、鼠标离开、鼠标点击、鼠标滚轮滚动、键盘按键按下等都属于事件。网页中的每个元素都可以产生某些可以触发 JavaScript 的事件,例如,我们可以在用户点击某按钮时产生一个事件,然后去执行某些操作。

  一个完整的事件包含三个要素:①事件源 ②事件类型 ③事件处理程序

1.2 执行事件的步骤

  1.获取事件源

  2.注册事件(绑定事件)

  3.添加事件处理程序(采用函数赋值的形式)

  练习:点击 div 控制台输出 “我被点击了”

<body>
    <div>????</div>
    <script>
        let div = document.querySelector("div")   // 获取事件源
        div.onclick = function(){       // onclick 表示事件类型为鼠标点击
            console.log("我被点击了");;             // 函数是处理程序
        }
    </script>
</body>

1.3 常见的鼠标事件更多事件查询

鼠标事件触发条件
onclick鼠标点击左键触发
onmouseover鼠标经过触发
onmouseout鼠标离开触发
onfocus获得鼠标焦点触发
onblur失去鼠标焦点触发
onmousemove鼠标移动触发
onmouseup鼠标弹起触发
onmousedown鼠标按下触发

  注意这些都是 JS 里的事件,与 CSS 里是有区别的。例如 CSS 中的鼠标经过是:div:houver{...} 而 JS 是用 onmouseover 注意区别。

二、操作元素

  JavaScript 的 DOM 操作可以改变网页内容、结构和样式,我们可以利用 DOM 操作元素来改变元素里面的内容 、属性等。下面有大量案例效果,最好先自己去尝试看看能不能实现,也有提供代码效果参考,有问题可以留言讨论。

H5新增获取元素方式示例

2.1 改变元素内容

  innerText 与 innetHTML 属性都可以更改元素的内容,都是可读写的,即既可以读出里面的内容,也可以写入内容,区别是:

  • element.innerText: 从起始位置到终止位置的内容, 但不识别 html 标签, 同时空格也会去掉
  • element.innerHTML: 起始位置到终止位置的全部内容,包括 html 标签,同时保留空格
<body>
    <p></p>
    <p></p>
    <div>
        <div>123</div>
        <span>678</span>
    </div>
    <script>
        let ps = document.querySelectorAll("p");
        let div = document.querySelector("div");
        ps[0].innerText = "<strong>注意:</strong>有坑";
        ps[1].innerHTML = "<strong>注意:</strong>有坑";
        console.log(div.innerText);
        console.log(div.innerHTML);
    </script>
</body>
innerText与innerHTML的区别

  案例:点击一个按钮,让另外一个元素内容显示当前日期,如下:

H5新增获取元素方式示例
<body>
    <button>显示当前系统日期</button>
    <div>某个时间</div>
    <script>
        let btn = document.querySelector("button");
        let nowTime = document.querySelector("div");
        btn.onclick = function() {
            nowTime.innerText = getDate();
        }
        function getDate(){     // 获取日期函数
            let date = new Date();
            let year = date.getFullYear();  // 获取年份
            let month = date.getMonth();    // 获取月份
            let dates = date.getDate();     // 获取日期
            let arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
            let day = date.getDay();        // 获取周几
            return '今天是:'+ year + '年' + month + '月' + dates + '日 ' + arr[day];
        }
    </script>
</body>

2.2 常用元素属性的修改

  • src 、href、id、alt、title 等都可以修改

  **案例1:**修改 img 元素的 src 属性,点击QQ按钮,下方显示qq图像。点击微信按钮,显示微信图像。

修改图像src属性
<body>
    <button> QQ </button><button> 微信 </button><br>
    <img src="./images/QQ.png" alt="">
    <script>
        let btns = document.querySelectorAll("button");
        let img = document.querySelector("img");
        btns[0].onclick = function(){
            img.src = "./images/QQ.png";
        }
        btns[1].onclick = function(){
            img.src = "./images/wechat.png";
        }
    </script>
</body>

  **案例2:**分时显示不同图片,显示不同问候语。打开页面,如果是上午时间,显示上午好,显示上午图片;如果是下午时间,显示下午好,显示下午图片;如果是晚上时间,显示晚上好,显示晚上图片;

<body>
    <p></p>
    <img src="./images/s.png" alt="">
    <script>
        let p = document.querySelector("p");
        let img = document.querySelector("img");
        let date = new Date();
        let h = date.getHours();
        if(h<12){
            p.innerHTML = "亲,上午好";
            img.src = "./images/s.png";
        }else if(h<18){
            p.innerHTML = "亲,下午好";
            img.src = "./images/x.png";
        }else{
            p.innerHTML = "亲,晚上好";
            img.src = "./images/w.png";
        }
    </script>
</body>

2.3 表单元素的属性操作

  利用 DOM 可以操作如下表单元素的属性:type、value、checked、selected、disabled。

  **案例1:**点击按钮,修改 input 里的值,并且设置按钮为禁用状态。

修改表单相关属性
<body>
    <button>按钮</button>
    <input type="text" value="请输入内容">
    <script>
        btn = document.querySelector("button");
        input = document.querySelector("input");
        btn.onclick = function(){
            input.value = "点击了";
            this.disabled = true;   // btn.disabled = true 一样
        }
    </script>
</body>

  **案例2:**制作密码隐藏与显示效果如下效果

密码显示与影藏
<style>
    * {
        margin: 0;
        padding: 0;
    }
    body {
        color: #9C9C9C;
    }
    
    a {
        text-decoration: none;
        color: #5e5a5a;
        display: inline-block;
    }
    h4 {
        font-weight: 400;
        margin-top: 20px;
        text-align: center;
    }
    input {
        height: 100%;
        width: 450px;
        border: transparent;
        color: #9C9C9C;
        outline: none;
        border-bottom:1px solid #9C9C9C;
        margin:0 25px 0 25px;
        box-sizing: border-box;
    }
    .box {
        width: 500px;
        height: 300px;
        border: 1px solid transparent;
        margin: 10px auto;
        /* text-align: center; */
    }
    .user,.psw,.delu,.zh {
        margin-top: 10px;
        width: 500px;
        height: 40px;
    }
    .psw {
        position: relative;
    }

    .psw img {
        position: absolute;
        top: 8px;
        right: 100px;
        width: 24px;
    }
    .psw span{
        position: absolute;
        display: inline-block;
        top: 12px;
        right: 95px;
        height: 17px;
        border-left: 1px solid #9C9C9C;
    }
    .psw a {
        height: 100%;
        position: absolute;
        top:0;
        right: 25px;
        line-height: 40px;
    }
    .delu input{
        border-radius: 16px;
        color: aliceblue;
        background-color: #F6C9BA;
        font-size: 15px;
        border-bottom:1px solid transparent;
    }
    .zh {
        position: relative;
        /* padding: 0 25px; */
    }
    .zh a:first-child {
        position: absolute;
        top:0;
        left: 25px;
    }
    .zh a:last-child {
        position: absolute;
        top:0;
        right: 25px;
    }
</style>
<body>
    <div class="box">
        <h4>京东登录</h4>
        <div class="user">
            <input type="text" value="用户名/邮箱/已验证手机">
        </div>
        <div class="psw">
            <img src="images/close.png" alt="" id="eye">
            <span></span>
            <a href="#"> 忘记密码</a>
            <input type="password" name="" id="psw">
        </div>
        <div class="delu">
            <input type="button" name="" id="" value="登录">
        </div>
        <div class="zh">
            <a href="#" class="dx">短信验证码登录</a>
            <a href="#" class="zc">手机快速注册</a>
        </div>
    </div>
    <script>
        let input = document.getElementById("psw");
        let img = document.getElementById("eye");
        let flag = 0;
        img.onclick = function(){
            if(flag == 0){
                input.type = "text";
                flag = 1;
                img.src = "images/open.png"
            }else{
                input.type = "password";
                flag = 0;
                img.src = "images/close.png"
            }
        }
    </script>
</body>

2.4 样式属性操作

  可以通过 JS 修改元素的大小、颜色、位置等样式。有两种方式:element.style :行内样式操作element.className :类名样式操作

  • element.style :行内样式操作
<style>
    div {
        width: 50px;
        height: 50px;
        background-color: pink;
    }
</style>
<body>
    <div></div>
    <script>
       let div = document.querySelector("div");
       div.onclick = function() {
           div.style.backgroundColor = "black";
           this.style.width = "100px";
       }
    </script>
</body>
JS修改行内样式

  【注意:】

  1.JS里面的样式采用驼峰命名法:fontSize、backgroundColor 等。

  2.JS 修改 style 样式操作,产生的是行内样式,权重比较高。

  案例: 仿淘宝删除广告功能:利用样式的显示和隐藏完成,display:none 和 block。

仿淘宝广告影藏
<style>
    .box {
        position: relative;
        width: 200px;
        height: 220px;
        margin: 20px auto;
        color: #DF5A3A;
    }
    .box img {
        width: 200px;
        height: 200px;
    }
    .close-btn {
        position: absolute;
        top: 15px;
        left: -20px;
        font-size: 25px;
    }
</style>
<body>
    <div class="box">
        淘宝二维码
        <img src="images/tao.png" alt="">
        <span class="close-btn">X</span>
    </div>
    <script>
       let span = document.querySelector("span");
       let box = document.querySelector("div");
       span.onclick = function() {
           box.style.display = "none";
       }
    </script>
</body>

  案例:循环精灵图背景:可以用 for 循环设置一组元素的精灵图背景精灵图链接

精灵图技术制作
<body>
    <ul class="box">
        <li>充话费<span></span></li>
        <li>旅行<span></span></li>
        <li>车险<span></span></li>
        <li>游戏<span></span></li>
        <li>彩票<span></span></li>
        <li>电影<span></span></li>
        <li>酒店<span></span></li>
        <li>理财<span></span></li>
        <li>找服务<span></span></li>
        <li>演出<span></span></li>
        <li>水电费<span></span></li>
        <li>火车票 <span></span></li>
    </ul>
    <script>
       let spans = document.querySelectorAll("span");
       for (let i = 0;i<spans.length;i++){
           let index = i * 44;
           spans[i].style.backgroundPosition = "0 -" + index + "px";
       }
    </script>
</body>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    li {
        list-style: none;
    }
    .box {
        height: 165px;
        width: 240px;
        margin: 20px auto;
    }
    .box li {
        overflow: hidden;
        position: relative;
        float: left;
        width: 60px;
        height: 60px;
        font-size: 8px;
        text-align: center;
        line-height: 90px;
        border: 1px solid #d8e3eefe;
        box-sizing: border-box;
        margin-left: -1px;
        margin-top: -1px;
    }
    .box li span {
        position: absolute;
        display: inline-block;
        top: 10px;
        left: 17px;
        width: 24px;
        height: 24px;
        background: url(images/sprite.png) no-repeat;
    }
</style>

  案例:显示隐藏文本框的内容:当鼠标点击文本框时,里面的默认文字隐藏,当鼠标离开时里面的默认文字显示。

显示隐藏文本内容
  • 用到两个新事件:获得焦点 onfocus 、失去焦点 onblur
<style>
    input {
        display: block;
        margin: 20px auto;
        color: #999;
    } 
</style>
<body>
    <input type="text" value="手机">
    <script>
        let input = document.querySelector("input");
        input.onfocus = function(){
            if(this.value === "手机"){
                this.value = "";
            }
            this.style.color = "#333";
        }
        input.onblur = function(){
            if(this.value === ""){
                this.value = "手机";
                this.style.color = "#999";
            }   
        }
    </script>
</body>
  • element.className :类名样式操作

  当我们需要修改一个元素的很多属性时,如果用 element.style 一个一个去修改会显得很麻烦,这种情况下,我们就可以选择使用类名样式去同意修改啦~

element.className = "要替换的类名";

  我们将要修改的样式统一写 CSS 中的一个类名里,然后把该元素的 className 值修改为这个类名即可,注意,className 属性修改的类名是覆盖原类名。

<style>         /* css */
    .first {
        width: 200px;
        height: 200px;
        margin: 45px auto;
        background-color: red;
    }
    .add1 {
        width: 100px;
        height: 100px;
        margin: 45px auto;
        background-color: blue;
    }
    .add2 {
        transform: rotate(-45deg);
    }
</style>
<body>      <!-- html -->
    <div class="first"></div>
    <script>    /* javascript */
        let div = document.querySelector("div");
        div.onclick = function(){       /* 鼠标点击时,类修改为 add1 */
            this.className = "add1";
        }
        div.onmousemove = function() {       /* 鼠标经过时,类加上 add2 */
            if(this.className.indexOf(" add2")==-1){ /* 注意没有 add2 类才加,不然一直在加 */
                this.className = this.className + " add2";
            }
        }
        div.onmouseout = function() {       /* 鼠标移除时,删掉 add2类 */
            console.log("chulaile ");
            this.className = this.className.replace(" add2","");
        }
    </script>
</body>
className修改属性

案例:制作如下密码框验证效果

className案例
<style>         /* css */
    input{
        outline: none;
    }
    .box{
        width: 600px;
        margin: 20px 200px;
    }
    .message {
        display: inline-block;
        font-size: 14px;
        color: #999;
        background: url(./images/mess.png) no-repeat left center;
        padding-left: 20px;
    }
    .wrong {
        background-image: url(./images/wrong.png);
        color: red;
    }
    .right {
        background-image: url(./images/right.png);
        color: green;
    }
</style>
<body>      <!-- html -->
    <div class="box">
        <input type="password" value="">
        <p class="message">请输入616位密码</p>
    </div>
    <script>    /* javascript */
        let input = document.querySelector("input");
        let p = document.querySelector("p");
        input.onfocus = function(){
            p.className = "message";
            p.innerHTML = "请输入6到16位密码";
        }
        input.onblur = function() {
            if (input.value.length<6 || input.value.length >16){
                p.className = "message wrong";
                p.innerHTML = "输入的密码需要6~16位长度哦~";
            }else{
                p.className = "message right";
                p.innerHTML = "输入的密码符合要求";
            }
        }
    </script>
</body>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ItDaChuang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值