安安123

JavaScriptDOM

DOM简介

1.HTML DOM:网页被加载时,浏览器会创建文档对象模型
2.DOM操作HTML:改变HTML的元素、属性、CSS样式、对所有事件作出反应

DOM操作HTML

1.改变HTML输出流
不要在文档加载完成后使用document.write()
2.寻找元素
(1)通过id
(2)通过标签名
3.改变HTML内容
innerHTML

<p id="pid">hello</p>
<p id="pid">hello</p>
<button onclick="demo()">按钮</button>
<script>
    function demo(){
        var nv=document.getElementById("pid").innerHTML="HELLO";
        document.getElementByTagName("p");//同类元素中的第一个
    }
</script>

4.改变HTML属性
attribute

<a id="aid" href="http://www.a.com">hello</a>
<button onclick="demo()">按钮</button>
<script>
    function demo(){
        document.getElementById("aid").href="http://www.b.com";
    }
</script>

DOM操作CSS

<div class="div" id="div">Hello</div>
<button onclick="demo()">按钮</button>
<script>
    function demo(){
        document.getElementById("div").style.background="#fff";
</script>

DOM EventListener

addEventListener():向指定元素添加事件句柄
removeEventListener():移除方法添加的事件句柄

<button id="btn">按钮</button>
<script>
    document.getElementById("btn").addEventListener("click",function(){
        alert("HELLO")
    });
</script>
<button id="btn">按钮</button>
<script>
    var x=document.getElementById("btn");
    x.addEventListener("click",hello);//添加句柄
    x.addEventListener("click",world);
    x.removeEventListener("click",world);//移除句柄

    function hello(){
        alert("hello");
    }
    function world(){
        alert("world");
    }
</script>

posted on 2017-07-10 21:34  安安123  阅读(183)  评论(0编辑  收藏  举报

导航