JavaScript-DOM

DOM

文档对象模型(Document Object Model,DOM)是一种用于HTML编程接口。

它给文档提供了一种结构化的表示方法,可以改变文档的内容和呈现方式。

更直白一点讲:

​ DOM相当于是一个模块,提供了关于HTML文档中对标签进行操作的功能,JavaScript结合DOM可以对HTML中的标签进行操作。

选择器

DOM中提供了一些列的选择器用于在HTML文档中找到指定的相关标签对象。

直接查找

document.getElementById(arg)             // 根据ID获取一个标签对象

document.getElementsByClassName(arg)     // 根据class属性获取标签对象集合

document.getElementsByName(arg)       // 根据name属性值获取标签对象集合

document.getElementsByTagName(arg)       // 根据标签名获取标签对象集合

间接查找

var tag = document.getElementById(arg);

tag.parentElement           // 找当前标签对象的父标签对象

tag.children                // 找当前标签对象的所有子标签对象

tag.firstElementChild       // 找当前标签对象的第一个子标签对象

tag.lastElementChild        // 找当前标签对象最后一个子标签对象

tag.nextElementtSibling     // 找当前标签对象下一个兄弟标签对象

tag.previousElementSibling  // 找当前标签对象上一个兄弟标签对象

表格中删除自身所在的行示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
    <style>
        table {
            /*边框合并*/
            border-collapse: collapse;
        }
        table th, table td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        table th {
            font-weight: bold;
        }
    </style>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>郭德纲</td>
        <td>男</td>
        <td>
            <input type="button" value="删除" onclick="deleteRow(this);">
        </td>
    </tr>
    <tr>
        <td>2</td>
        <td>于谦</td>
        <td>女</td>
        <td>
            <input type="button" value="删除" onclick="deleteRow(this);">
        </td>
    </tr>
    <tr>
        <td>3</td>
        <td>烧饼</td>
        <td>男</td>
        <td>
            <input type="button" value="删除" onclick="deleteRow(this);">
        </td>
    </tr>
    </tbody>
</table>
<script type="text/javascript">
    /*
    删除表格中当前行的数据
     */
    function deleteRow(self) {
        var rowTr = self.parentElement.parentElement;
        rowTr.remove();
    }
</script>
</body>
</html>

文本操作

对标签内部文本进行操作时,可以通过 innerText 和 innerHTML来进行。

  • innerText
    • 标签对象.innerText,读取标签内容(仅文本)。
    • 标签对象.innerText="武",修改标签内容(仅文本)。
  • innerHTML
    • 标签对象.innerHTML,读取标签内容(含标签)。
    • 标签对象.innerText="<a href='#'>武</a>",修改标签内容(可标签、可文本)。

读取表格文本内容示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
    <style>
        table {
            /*边框合并*/
            border-collapse: collapse;
        }
        table th, table td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        table th {
            font-weight: bold;
        }
    </style>
</head>
<body>
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>网站</th>
        <th>介绍</th>
        <th>读取</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>
            <a href="http://www.baidu.com">百度</a>
        </td>
        <td>百度是一个流氓网站。</td>
        <td>
            <input type="button" value="读取网站innerText" onclick="readSite(this)">
            <input type="button" value="读取网站innerHTML" onclick="readSummary(this)">
        </td>
    </tr>
    </tbody>
</table>
<script type="text/javascript">
    function readSite(self) {
        var tdTag = self.parentElement.previousElementSibling.previousElementSibling;
        console.log(tdTag.innerText);
    }
    function readSummary(self) {
        var tdTag = self.parentElement.previousElementSibling.previousElementSibling;
        console.log(tdTag.innerHTML);
    }
</script>
</body>
</html>

值操作

值操作针对与用户交互相关的标签,其中内部使用value属性进行操作。

文本框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
</head>
<body>
    <input id="user" type="text" value="张鹤伦">
    <script type="text/javascript">
        var userTag = document.getElementById('user');
        console.log('获取输入框中的值:',userTag.value);
        // 修改input中的值
        userTag.value = "骚浪贱";
        console.log('获取修改完输入框中的值:',userTag.value);
    </script>
</body>
</html>

多行文本框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
</head>
<body>
<h1>文章</h1>
<textarea id="article" cols="30" rows="10">从前有座山,山里有座庙。</textarea>
<input type="button" onclick="showArticle();" value="点击获取"/>
<input type="button" onclick="setArticle();" value="点击设置"/>
<script type="text/javascript">
    function showArticle() {
        // 获取textarea的值
        console.log(document.getElementById('article').value);
    }
    function setArticle() {
        // 设置textarea的值
        document.getElementById('article').value = "秃驴";
    }
</script>
</body>
</html>

下拉框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
</head>
<body>
<h1>城市</h1>
<select id="city">
    <option value="10">上海</option>
    <option value="20">北京</option>
    <option value="30">深圳</option>
</select>
<input type="button" onclick="showCity();" value="点击获取选择"/>
<input type="button" onclick="setCity();" value="点击设置"/>
<script type="text/javascript">
    function showCity() {
        // 获取select下拉框选中项的值
        var cityTag = document.getElementById('city');
        console.log(cityTag.value);
    }
    function setCity() {
        // 设置select下拉框选中项的值,让select去选中。
        document.getElementById('city').value = "30";
    }
</script>
</body>
</html>

单选框

通过value可以取值。但在应用时常常是以选择形式出现,所以在使用过程中还会去判断他是否已被选中。

标签对象.checked 可以对选中状态进行读取和设置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
</head>
<body>
<input type="radio" name="gender" value="11"/>男
<input type="radio" name="gender" value="33"/>女
<input type="radio" name="gender" value="66"/>中
<input type="button" onclick="showGender();" value="点击获取选择"/>
<input type="button" onclick="setGender();" value="点击设置选择状态"/>
<script type="text/javascript">
    function showGender() {
        var radios = document.getElementsByName('gender');
        // 循环所有的radio标签,找到被选中的radio,获取他的value值。
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].checked) {
                // 弹出选中值
                console.log(radios[i].value);
                // 选中后退出循环
                break;
            }
        }
    }
    function setGender(){
        var radios = document.getElementsByName('gender');
        // 循环所有的radio标签,找到被选中的radio,获取他的value值。
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].value === "33") {
              radios[i].checked = true;
            }
        }
    }
</script>
</body>
</html>

复选框

通过value可以取值。但在应用时常常是以多选形式出现,所以在使用过程中还会去判断他是否已被选中。
扩展:标签对象.checked 可以对选中状态进行读取和设置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
</head>
<body>
<h1>爱好</h1>
<input class="hobby" type="checkbox" value="1">足球
<input class="hobby" type="checkbox" value="2">篮球
<input class="hobby" type="checkbox" value="3">乒乓球
<input type="button" onclick="showHobby();" value="点击获取选择"/>
<input type="button" onclick="setHobby();" value="点击设置选择"/>
<script type="text/javascript">
    function showHobby() {
        var valueList = [];
        var checkboxList = document.getElementsByClassName('hobby');
        for (var i = 0; i < checkboxList.length; i++) {
            if (checkboxList[i].checked) {
                // 弹出选中值
                valueList.push(checkboxList[i].value);
            }
        }
        console.log(valueList);
    }
    function setHobby() {
         var checkboxList = document.getElementsByClassName('hobby');
        for (var i = 0; i < checkboxList.length; i++) {
            if(checkboxList[i].value === '1' || checkboxList[i].value === '3') {
                checkboxList[i].checked = true;
            }else{
                checkboxList[i].checked = false;
            }
        }
    }
</script>
</body>
</html>

表格批量操作示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
    <style>
        table {
            /*边框合并*/
            border-collapse: collapse;
        }
        table th, table td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        table th {
            font-weight: bold;
        }
    </style>
</head>
<body>
<div>
    <input type="button" value="全选" onclick="checkAll();"/>
    <input type="button" value="取消" onclick="cancelAll();"/>
    <input type="button" value="反选" onclick="reverseCheck();"/>
</div>
<table>
    <thead>
    <tr>
        <th>选择</th>
        <th>姓名</th>
        <th>性别</th>
    </tr>
    </thead>
    <tbody id="tableBody">
    <tr>
        <td><input type="checkbox" value="1"/></td>
        <td>郭德纲</td>
        <td>男</td>
    </tr>
    <tr>
        <td><input type="checkbox" value="2"/></td>
        <td>于谦</td>
        <td>女</td>
    </tr>
    <tr>
        <td><input type="checkbox" value="2"/></td>
        <td>烧饼</td>
        <td>男</td>
    </tr>
    </tbody>
</table>
<script type="text/javascript">
    /* 全选 */
    function checkAll() {
        var trTagList = document.getElementById('tableBody').children;
        for (var i = 0; i < trTagList.length; i++) {
            var trTag = trTagList[i];
            var inputTag = trTagList[i].firstElementChild.firstElementChild;
            inputTag.checked = true;
        }
    }
    /* 取消 */
    function cancelAll() {
        var trTagList = document.getElementById('tableBody').children;
        for (var i = 0; i < trTagList.length; i++) {
            var trTag = trTagList[i];
            var inputTag = trTagList[i].firstElementChild.firstElementChild;
            inputTag.checked = false;
        }
    }
    /* 取消 */
    function reverseCheck() {
        var trTagList = document.getElementById('tableBody').children;
        for (var i = 0; i < trTagList.length; i++) {
            var trTag = trTagList[i];
            var inputTag = trTagList[i].firstElementChild.firstElementChild;
            // inputTag.checked = ! inputTag.checked;
            inputTag.checked = inputTag.checked ? false : true;
        }
    }
</script>
</body>
</html>

class属性操作

DOM中主要提供了三个帮助我们操作class属性值的功能:

  • 标签对象.className,class属性对应的值直接操作。
  • 标签对象.classList.remove(cls),class属性对应值删除某个样式。
  • 标签对象.classList.add(cls),class属性中添加样式。

模态对话框示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            margin: 0;
        }
        .container{
            width: 980px;
            margin: 0 auto;
        }
        .header{
            height: 48px;
            background-color: #499ef3;
        }
        .shade{
            position: fixed;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: black;
            opacity: 0.7;
        }
        .login{
            width: 400px;
            height: 300px;
            background-color: white;
            border: 1px solid #dddddd;
            position: fixed;
            top: 60px;
            left: 50%;
            margin-left: -200px;
        }
        .hide{
            display: none;
        }
    </style>
</head>
<body>
    <div class="header">
        <div style="float: right;margin: 10px;">
            <a onclick="showDialog();" style="padding: 5px 10px;background-color: goldenrod;color: white;">登录</a>
        </div>
    </div>
    <div class="body">
        <div class="container" style="text-align: center">
            <img src="https://images.cnblogs.com/cnblogs_com/wupeiqi/662608/o_big_girl.png" alt="">
        </div>
    </div>
    <!--遮罩层-->
    <div id="shade" class="shade hide"></div>
    <!--登录框-->
    <div id="login" class="login hide">
        <h2 style="text-align: center">用户登录</h2>
        <a onclick="hideDialog();" style="padding: 5px 10px;background-color: cornflowerblue;color: white;">关闭</a>
    </div>
    <script type="text/javascript">
        function showDialog() {
            document.getElementById('shade').classList.remove('hide');
            document.getElementById('login').classList.remove('hide');
        }
        function hideDialog() {
            document.getElementById('shade').classList.add('hide');
            document.getElementById('login').classList.add('hide');
        }
    </script>
</body>
</html>

style 样式操作

对样式操作的粒度更细一些,可以使用style样式操作,他比class属性对样式的操作粒度更细。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
</head>
<body>
    <div id="header" style="height: 48px;background-color: red;"></div>
    <script type="text/javascript">
        document.getElementById('header').style.backgroundColor = 'green';
    </script>
</body>
</html>

点赞+1效果示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript学习</title>
    <style>
        body {
            margin: 0;
        }
        .container {
            width: 980px;
            margin: 0 auto;
        }
        .item {
            height: 120px;
            border: 1px solid #dddddd;
            margin-top: 20px;
            padding: 10px;
        }
        .item .title {
            margin-bottom: 10px;
            font-weight: bold;
        }
        .item img {
            width: 60px;
            height: 60px;
        }
        .item .favor {
            position: relative;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="item">
        <div class="title">震惊了...</div>
        <img src="https://images.cnblogs.com/cnblogs_com/wupeiqi/662608/o_20130809170025.png" alt="">
        <div class="favor" onclick="doFavor(this);">赞</div>
    </div>
    <div class="item">
        <div class="title">冷酷无情,无理取闹...</div>
        <img src="https://images.cnblogs.com/cnblogs_com/wupeiqi/662608/o_20130809170025.png" alt="">
        <div class="favor" onclick="doFavor(this);">赞</div>
    </div>
</div>
<script type="text/javascript">
    function doFavor(self) {
        var plusTag = document.createElement('span');
        var fontSize = 10;
        var marginLeft = 10;
        var marginTop = 10;
        var opacity = 1;
        plusTag.innerText = "+1";
        plusTag.style.color = 'green';
        plusTag.style.position = 'absolute';
        plusTag.style.fontSize = fontSize + 'px';
        plusTag.style.marginLeft = marginLeft + 'px';
        plusTag.style.marginTop = marginTop + 'px';
        plusTag.style.opacity = opacity;
        self.appendChild(plusTag);
        var interval = setInterval(function () {
            fontSize += 5;
            marginLeft += 5;
            marginTop -= 5;
            opacity -= 0.2;
            plusTag.style.fontSize = fontSize + 'px';
            plusTag.style.marginLeft = marginLeft + 'px';
            plusTag.style.marginTop = marginTop + 'px';
            plusTag.style.opacity = opacity;
            if (opacity <= 0) {
                self.removeChild(plusTag);
                clearInterval(interval);
            }
        }, 100)
    }
</script>
</body>
</html>

事件

DOM中可以为标签设置事件,给指定标签绑定事件之后,只要对应事件被触发,就会执行对应代码。常见事件有:

  • onclick,单击时触发事件
  • ondblclick,双击触发事件
  • onchange,内容修改时触发事件
  • onfocus,获取焦点时触发事件
  • onblur,失去焦点触发事件

修改下拉框触发change事件

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'/>
    <title>DOM学习</title>
</head>
<body>
<select id="city" onchange="changeEvent(this);">
    <option value="10">普通青年</option>
    <option value="20">文艺青年</option>
    <option value="30">二逼青年</option>
</select>
<script type="text/javascript">
    function changeEvent(self) {
        console.log(self.value);
    }
</script>
</body>
</html>

左侧菜单点击切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS学习</title>
    <style>
        body {
            margin: 0;
        }
        .header {
            height: 48px;
            background-color: #499ef3;
        }
        .body .menu {
            position: fixed;
            top: 48px;
            left: 0;
            bottom: 0;
            width: 220px;
            border-right: 1px solid #dddddd;
            overflow: scroll;
        }
        .body .content {
            position: fixed;
            top: 48px;
            right: 0;
            bottom: 0;
            left: 225px;
            /* 超出范围的话,出现滚轮 */
            overflow: scroll;
        }
        .body .menu .title {
            padding: 8px;
            border-bottom: 1px solid #dddddd;
            background-color: #5f4687;
            color: white;
        }
        .body .menu .child {
            border-bottom: 1px solid #dddddd;
        }
        .body .menu .child a {
            display: block;
            padding: 5px 10px;
            color: black;
            text-decoration: none;
        }
        .body .menu .child a:hover {
            background-color: #dddddd;
        }
        .hide {
            display: none;
        }
    </style>
</head>
<body>
<div class="header"></div>
<div class="body">
    <div class="menu">
        <div class="item">
            <div class="title" onclick="showMenu(this);">国产</div>
            <div class="child">
                <a href="#">少年的你</a>
                <a href="#">我不是药神</a>
                <a href="#">我和我的祖国</a>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="showMenu(this);">欧美</div>
            <div class="child hide ">
                <a href="#">战争之王</a>
                <a href="#">华尔街之狼</a>
                <a href="#">聚焦</a>
            </div>
        </div>
        <div class="item">
            <div class="title" onclick="showMenu(this);">韩国</div>
            <div class="child hide">
                <a href="#">坏家伙们</a>
                <a href="#">寄生虫</a>
                <a href="#">燃烧</a>
            </div>
        </div>
    </div>
    <div class="content"></div>
</div>
<script type="text/javascript">
    function showMenu(self) {
        var childList = document.getElementsByClassName('child');
        for (var i = 0; i < childList.length; i++) {
            childList[i].classList.add('hide');
        }
        self.nextElementSibling.classList.remove('hide');
    }
</script>
</body>
</html>

请输入搜索关键字

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'/>
    <title>DOM</title>
    <style>
        .gray {
            color: gray;
        }
        .black {
            color: black;
        }
    </style>
</head>
<body>
<input type='text' class='gray' value='请输入关键字' onfocus='getFocus(this);' onblur='leave(this);'/>
<script type="text/javascript">
    function getFocus(self) {
        self.className = 'black';
        if (self.value === '请输入关键字' || self.value.trim().length === 0) {
            self.value = '';
        }
    }
    function leave(self) {
        if (self.value.length === 0) {
            self.value = '请输入关键字';
            self.className = 'gray';
        } else {
            self.className = 'black';
        }
    }
</script>
</body>
</html>
posted @ 2020-06-07 22:31  Hedger_Lee  阅读(176)  评论(0编辑  收藏  举报