2013-01-17 40 views
0

這是一個jscript關閉窗口,當有人點擊任何地方外部Div關閉。 我的問題是當有人通過執行此操作點擊此窗口時關閉此窗口。點擊任何地方關閉div內外

<div id="box" 
style="height: 3em; position:absolute; top: 20%; left: 15%; border: 3px double"> 
<p>Click anywhere outside this box to close it. 
</div> 
<script> 
document.onclick = function (e) { 
e = e || event 
var target = e.target || e.srcElement 
var box = document.getElementById("box") 
do { 
     if (box == target) { 
      // Click occured inside the box, do nothing. 
      return 
     } 
     target = target.parentNode 
} while (target) 
// Click was outside the box, hide it. 
box.style.display = "none" 
} 
</script> 

如何使一個DIV接近時,DIV

+2

你可以使用Jquery嗎?它會讓你的生活更輕鬆... – JohnJohnGa

+0

這是一種實踐還是商業工作?從頭開始實現你的需求是非常煩人的,考慮到這些跨瀏覽器的問題,你應該肯定會得到一些JS庫或框架。 –

回答

0

在你的HTML代碼本身,

<div id='box' style='height:10px; width:10px' onclick='CloseMe(this)'>...</div> 

落實CloseMe功能

function CloseMe(obj) 
{ 

    obj.style.display = 'none'; 
} 
+0

它的工作你做了一個偉大的工作。 –

+0

如果文本是錨點,該怎麼辦?當我在錨文本上嘗試它們時,它不起作用。 –

+0

你想通過點擊作爲錨點顯示的'X'文本來關閉div嗎? – SHANK

0

內發生了點擊,具體的事情這裏說,我沒有測試,但我想改變這種循環,下面的代碼可以使它。

do { 
    if (box != target) { 
     // Click occured outside the box, do nothing. 
     return 
    } 
    target = target.parentNode 
} while (target) 
0

如果您使用JQuery,你可以爲你的div

click功能使用 event.stopPropagation();
$(function(){ 
    $('html').click(function() { 
    $('#box').hide(); 
    }); 

    $('#box').click(function(event){ 
     event.stopPropagation(); 
    }); 
}); 

http://jsfiddle.net/nCqwy/1/

相關問題