我想讓彈出式div在我點擊它之外時消失。我需要純粹的js,而不是jQuery或其他東西。 所以我下面......javascript element body.onclick attatch event setTimeout
功能,使股利dissapear:
function closePopUps(){
if(document.getElementById('contact-details-div'))
document.getElementById('contact-details-div').style.display = 'none';
//...same code further...
}
function closePopUpsBody(e){
//finding current target - http://www.quirksmode.org/js/events_properties.html#target
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
//is we inside div?
while (targ.parentNode) {
//filtering "Close" button inside div
if (targ.className && targ.className == 'closebtn')
break;
if (targ.className && targ.className == 'contact-profile-popup')
break;
targ = targ.parentNode;
}
//if it not a div, or close button, hide all divs and remove event handler
if ((targ.className && targ.className == 'closebtn')
|| !(targ.className && targ.className == 'contact-profile-popup')) {
if(document.getElementById('contact-details-div'))
document.getElementById('contact-details-div').style.display = 'none';
//...some more code here...
document.body.onclick = null;
}
}
也許這段代碼是醜陋的,但是這不是一個主要的問題......
主要問題是,當我附加一個事件到身體,它立即執行!和div立即消失,我甚至沒有看到它。
<tr onclick="
closePopUps();
document.getElementById('contact-details-div').style.display='block';
document.body.onclick = closePopUpsBody;
return false;">
我雖然如果我不使用括號,它不會執行?
document.body.onclick = closePopUpsBody(); //this executes
document.body.onclick = function(){closePopUpsBody()}; //this is not
document.body.onclick = closePopUpsBody; //this is not
我終於完成了
<tr onclick="
closePopUps();
document.getElementById('contact-details-div').style.display='block';
setTimeout('document.body.onclick = closePopUpsBody;', 500);
return false;">
這個決定,但我認爲這太瘋狂了。所以,我做錯了什麼?
你可以給一個現場的例子,甚至更好,一個jsfiddle的鏈接? `document.body.onclick = closePopUpsBody`應該按預期工作。 – 2010-11-24 14:02:25