我有一个 div
,当我单击某个输入选择时,它会向下滑动(打开)。在这个 div
中,我有一些其他输入选择,我的目标是当我单击页面的其余部分时向上滑动 div
。
我的问题:
当我在其中的输入选择中选择某些项目时,div
会向上滑动,但我不希望发生这种情况。
- 是否有某种方法仅当我在
div
外部单击时才向上滑动? - 为什么 div 内的选择也会使其向上滑动?
这是我向上滑动 div 的 javascript:
$(document).mouseup(function (e) {
var container = $('.myDiv');
if (container.has(e.target).length === 0) {
$(container).removeClass('close');
$(container).addClass('open');
$(container).next().slideUp(200);
}
});
最佳答案
The div slides up when I select some item in the input selects inside it, and I don't want this to happen.
Is there some way to slide up the div only when I click outside it? Why are the selects inside the div making it to slide up as well?
使用event.stopPropagation()位于子元素上,以防止它们触发滑动事件。
event.stopPropagation - Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
这是一个简单的 jsFiddle以及下面的基本示例。
jQuery:
$('div').click(function(){
$('#slideMeUp').slideUp();
});
$('select').click(function(e){
e.stopPropagation();
});
HTML:
<div>Clicking here will trigger it!
<select>
<option>This won't trigger the click event anymore!</option>
</select>
Clicking here will also trigger it!
</div>
<div id="slideMeUp">Only clicking the outer div will slide me up!</div>
关于javascript - 单击其中的项目时 Div 向上滑动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16565663/