2014-03-29 43 views
0

所以我有一个简单的标记:使用Javascript - 只隐藏在父点击

<div id="edit_image" class="image_manipulator"> 
    <input type="text" /> 
</div> 

这是JavaScript:

var image_manipulators= document.getElementsByClassName("image_manipulator"); 
for(var i = 0; i < image_manipulators.length; i++) { 
    image_manipulators[i].onclick = function() { 
     this.style.display = "none"; 
    }; 
} 

这是CSS:

.image_manipulator { 
    position: fixed; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%; 
    background: rgba(0, 0, 0, 0.9); 
    z-index: 1; 
    display: none; 
} 
#edit_image input { 
    display: table-cell; 
    vertical-align: middle; 
    margin: 0 auto; 
} 

这里是fiddle

如果你点击半透明盒子,那么你可以看到它正常消失,但如果你试图在文本框上写东西,那么半透明盒子仍然消失。我怎么能阻止这种情况发生。 :)

P.S:没有jQUery允许。 :)

回答

4

您可以尝试event.stopPropagation();

DEMO

HTML

<div id="edit_image" class="image_manipulator"> 
    <input id="textBox" type="text" /> 
</div> 
<button id="showBox">Click me</button> 

Java脚本

var image_manipulators = document.getElementsByClassName("image_manipulator"); 
for (var i = 0; i < image_manipulators.length; i++) { 
    image_manipulators[i].onclick = function() { 
     this.style.display = "none"; 
    }; 
} 

document.getElementById("showBox").onclick = function() { 
    document.getElementById("edit_image").style.display = "block"; 
} 

document.getElementById("textBox").onclick = function(e) { 
    e.stopPropagation(); 
} 
+0

谢谢,工作。 :)其实我增强了一点。看到这个:http://jsfiddle.net/mareebsiddiqui/XVS2C/5/ –

+0

太棒了!希望它有助于:) –

+2

为了扩大答案并解释它的工作原理,当你点击不是事件结束的“文本框”时,事件通过所有父节点渗透到“文档“,除非你像Pravin那样明确地'stopPropagation()'在这里完成了。 – Victory

0

尝试使用这样的:

var image_manipulators= document.getElementsByClassName("image_manipulator"); for(var i = 0; i < image_manipulators.length; i++) { image_manipulators[i].onclick = function(e) { this.style.display = "none"; e.stopPropagation(); }; }

+0

我不认为这将解决。不起作用:/ –

1

您应该取消默认行为时,点击输入,看到http://jsfiddle.net/XVS2C/8/

document.getElementById("test").onclick = function(e){ 
if (!e) 
    e = window.event; 

//IE9 & Other Browsers 
if (e.stopPropagation) { 
    e.stopPropagation(); 
} 
//IE8 and Lower 
    else { 
    e.cancelBubble = true; 
    } 
} 

设置ID输入

<input type="text" id="test" /> 
+0

如果你正在看这个和普拉文的答案,并且想知道'cancelBubble' vs'stopPropagation'的处理是什么,请查看http://www.quirksmode.org/js/events_order.html – Victory

+2

只是对所有浏览器做了一些更改,版本只适用于IE和Chrome。看看http://jsfiddle.net/XVS2C/8/ – iwcoder