JavaScript学习笔记(02DOM-P60-P63)

JS中的DOM对象

 

 

 DOM操作HTML的几个方面,一共四个

 

 

 

 

 

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <p id="pid">Hello</p>
    <p id="pid1">Time</p>
    <a id="aid" href="http://www.baidu.com">链接</a>
    <button onclick="demo()">按钮</button>
    <script>
        function demo() {
            //document.getElementById("pid").innerHTML = "World";
            //document.getElementsByTagName("p")[0].innerHTML = "Thanks";//获得所有p标签元素的集合
            document.getElementById("aid").href = "http://www.taobao.com";//改变属性
        }
    </script>
</body>
</html>
View Code

 

DOM操作CSS

 

 

 HTML代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link href="../Css/MyStyleSheet1.css" type="text/css" rel="stylesheet" />
</head>
<body>
    <div id="divid" class="container">
        Hello
    </div>
    <button id="btnid" onclick="demo()">按钮</button>
    <script>
        function demo() {
            document.getElementById("divid").style.backgroundColor = "pink";
        }
    </script>
</body>
</html>
View Code

CSS代码

.container{
    width:100px;
    height:100px;
    background-color:red;
}
View Code

注意到在JS的style中有background和backgroundColor两个属性,但是这两个属性其实对应的都是背景色这一个值。什么原因呢,简单说就是CSS为了兼容JS中不能使用“-”符作为变量命名,所以这里的命名有兼容:具体文章

 

DOM中的句柄(事件监听器)

 

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <button id="btn">按钮</button>
    <script>
        var btn = document.getElementById("btn");
        btn.addEventListener("click", hello);//实际开发中多用这种模式
        btn.addEventListener("click", world);//可以在同一种事件中添加多个函数的响应
        btn.removeEventListener("click", hello);//移除事件响应的函数
        function hello() {
            alert("Hello");
        }
        function world() {
            alert("World");
        }
    </script>
</body>
</html>
View Code

 

End

posted @ 2020-02-07 21:16  ZedFFF  阅读(133)  评论(0)    收藏  举报