取消将div固定在文档上单击 [英] Unpinning a div on document click
问题描述
我有一个div,可在悬停时切换并在点击时固定.我正在尝试添加一个在用户单击页面其余部分时取消div固定的功能.
I have a div that toggles on hover and gets pinned on click. I'm trying to add a function that unpins the div when the user clicks on the rest of the page.
我尝试使用这个:
$( document ).on('click', function( e ) {
if( e.target.id != 'dialog-box' ){
$( ".dialog-box" ).hide();
}
});
但是,即使单击激活div,它也会隐藏div.
However it hides the div even when click on the activation div.
这是我用于固定的jQuery:
Here is the jQuery I'm using for the pin:
$(document).ready(function(){
$(".two").hover(function() {
if (!$(this).data('pinned')) $(".dialog-box").toggle("slow");
});
$(".two").click(function() {
$(this).data('pinned', !$(this).data('pinned'));
});
});
这是我正在工作的小提琴,不包括上面的第一个脚本:
Here is a fiddle with what I have working not including the first script above:
推荐答案
单击div时,只需停止事件冒泡,这样就可以知道click事件是否到达了文档,这并不是单击div
Just stop event bubbling when you click on the div, that way you know if a click event gets to the document, it wasn't from clicking on the div.
http://api.jquery.com/event.stopPropagation/
$( document ).on('click', function( e ) {
$( ".dialog-box" ).hide();
});
$(".two").click(function(e) {
e.stopPropagation();
$(this).data('pinned', !$(this).data('pinned'));
});
这篇关于取消将div固定在文档上单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!