当您单击某些图像时,我正在尝试创建一个子菜单。如果用户单击菜单中以外的任何地方,我希望菜单隐藏。
现在我有了这段代码,它可以正常工作,只是即使您单击菜单时它也会隐藏。
如果您能帮助我,我将不胜感激!
JAVASCRIPT
/**
* Create tooltips on mouseover or on click (for supporting touch interfaces).
*
* @author C. Scott Asbach
*/
$(document).ready(function () {
// flag to consume the first click, so it doesn't hide the tooltip immediatly
var click_hides = 2;
$('html').click(function (e) {
// *************************************************************************
// ********** I think the problem is in the second part of this if **********
// *************************************************************************
if (click_hides === 1 && !$(e.target).hasClass('tooltip'))
{
$('.tooltip').remove();
}
click_hides++;
});
/**
* store the value of and then remove the title attributes from the
* abbreviations (thus removing the default tooltip functionality of
* the abbreviations)
*/
$('abbr').each(function () {
$(this).data('title', $(this).attr('title'));
$(this).removeAttr('title');
});
/**
* when abbreviations are clicked trigger their mouseover event then fade the tooltip
* (this is friendly to touch interfaces)
*/
$('abbr').click(function () {
click_hides = 0;
// first remove all existing abbreviation tooltips
$('abbr').next('.tooltip').remove();
// create the tooltip
$(this).after('<span class="tooltip">' + $(this).data('title') + '</span>');
// position the tooltip 4 pixels above and 4 pixels to the left of the abbreviation
var left = $(this).position().left + $(this).width() + 4;
var top = $(this).position().top - 4;
$(this).next().css('left', left);
$(this).next().css('top', top);
});
});
CSS
abbr
{
border-bottom: 1px dotted #666;
cursor: help;
}
.tooltip
{
position:absolute;
background-color:#eeeefe;
border: 1px solid #aaaaca;
font-size: smaller;
padding:4px;
width: 160px;
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
-moz-box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
-webkit-box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="tooltip.css" />
</head>
<body>
<p>For a tooltip hover or click <abbr title="This text will show up in your tooltip!">here</abbr>.</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='touchHover.js'></script>
</body>
</html>