JavaScript event bubbling, delegate

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #box1{
                width: 100px;
                height: 100px;
                background-color: yellowgreen;
                /*
                 * 要设置偏移量left,top,要开启绝对定位
                 */
                position: absolute;
            }
            #box2{
                width: 500px;
                height: 500px;
                background-color: pink;
            }
        </style>
    </head>
    <body>
        <div id="box1">
            我是box1
        </div>
        <div id="box2">
            我是box2
            <ul id="allA">
                <li><a href="javascript:;" class="link">超链接1</a></li>
                <li><a href="javascript:;" class="link">超链接2</a></li>
                <li><a href="javascript:;" class="link">超链接3</a></li>
            </ul>
        </div>
    </body>
    <script type="text/javascript">var# box1 follow the mouse//* /
         * as: # box1 can move to follow the mouse # box2 will take to achieve document
         * pointing upwards transduction events, the event in response to the sub-elements, ancestor elements are also the same event responseBubbling event (Bubble)/ *
        
         
        
        = document.getElementById box1 ( "box1" );
        document.onmousemove = function (Event) {
             // address compatibility issues 
            Event Event = || the window.event; 
            
            // CSS offset is set, the coordinate setting 
             // the clientX visible window is relatively coordinates, the coordinates of the scroll bar when rain div opposite page does not correspond to this time have pageX 
            box1.style.left = event.pageX + "PX" ; 
            box1.style.top = event.pageY + "PX" ; 
        } 
        / * cancel bubbling
          * / 
        var BOX2 = document.getElementById ( "BOX2" ); 
        box2.onmousemove = function (Event) { 
            event.cancelBubble = to true ; //Not moving in the box2 
        } 
        
        // delegated event 
         // use bubbling, only one binding event ancestor elements, carrying out the same sub-event pile element 
         var Alla = document.getElementById ( 'Alla' ); 
         Alla. onclick = function () {
              // If the triggering event was the object is the desired element is then executed, or not executed, where li will be executed, but we have to execute a 
              // event.target determination target 
              IF (event.target.className == 'link' ) { 
                  Alert ( "hyperlink" ); 
              } 
             
         }
         
     </ Script> 
</ HTML>

 

Guess you like

Origin www.cnblogs.com/wangdongwei/p/11291096.html