Javascript 点击div之外任何地方,隐藏div    




document.onclick = function (event) { 

 var e = event || window.event;   //e就是事件源对象
//window.event为 IE对象 和 event为 firefox对象 

 var elem = e.srcElement || e.target; // elem 就是事件的触发源 
 // e.srcElement为 IE触发源 和 e.target 为firefox触发源

    while (elem) {

          if (elem != document) {

                if (elem.id == "目标ID") {

                     show();//执行显示

                     return;

                }

                elem = elem.parentNode;

          } else {

             hide();//执行隐藏

             return;

            }

        }

    }





jq方法

        function stopPropagation(e) {
                if (e.stopPropagation) 
                    e.stopPropagation();
                else 
                    e.cancelBubble = true;
            }

            $(document).bind('click',function(){
                $('#div1').css('display','none');
            });

            $('#div1').bind('click',function(e){
                stopPropagation(e);
            });