day16--Dom事件操作

1、事件:

行为 样式  结构 相分离的页面

js       css     html

绑定事件的两种方式:

 (1)直接标签绑定,onclick='xxx()';

 (2)先获取Dom对象,然后进行绑定

   document.getElementById('xx').onclick

   document.getElementById('xx').onfocus

直接使用标签绑定,实例如下:

   <head>
        <style>
            #test{
                background-color: red;
                 300px;
                height: 400px;
            }
        </style>
    </head>
    <body>
        <div id="test" onclick="t1();">
            asdf
        </div>
        <script>
            function t1(){
                console.log('asdfaa');
            }
        </script>

<style>中,为div的样式

当点击该div时,在控制台中显示asdfaa字符串

下面我们使用另外一种方式,先获取Dom对象,然后进行绑定:

   <body>
        <div id="test">
            asdf
        </div>
        <script>
            var mydiv=document.getElementById('test');
            console.log(mydiv);
            mydiv.onclick=function(){
                console.log('asdfg');
            }
        </script>
    </body>

这样将html与js分离开来

原文地址:https://www.cnblogs.com/wuxiaoru/p/12593557.html