我有这个小提琴: http://jsfiddle.net/u8t77p75/
我希望实现这一点,当我点击“body”时,js将检查实际的提示是否可见,如果是,则将其隐藏起来。
我想尝试类似的事情:
if ($tooltipContainer.hasClass('active')) {
$('body').click(function() {
$tipLink.triggerHandler('click');
});
}
它有效但不完美。当我插入此代码段时,它会调用触发器,但我需要多次单击才能打开或关闭。我认为这是因为调用了整个click-function。我还需要做点什么吗?
答案 0 :(得分:1)
您可以在文档中添加一个点击处理程序,用于检查您是否在工具提示外部单击并且打开了一个。代码是这样的:
$(document).click(function(e){
if ($(e.target).not(':has(.lhde__tooltip)').length == 0 && $('div.opened').length) {
// current click target is not the tooltip and a tip is open
$('div.opened').remove();
}
});
您的代码有效但我会从bootstrap查看popovers,因为它更容易创建弹出框。查看有效的演示here
请在下面jsFiddle找到您的代码。
(function ($) {
'use strict';
var $tipLink = $('.lhde__tooltip'),
$tipContent = $('.lhde__tooltip__content');
//initial hide tipContent
$tipContent.hide();
$tipLink.click(function (e) {
// prevent click event
e.preventDefault();
var $clicked = $(this),
href = $(this).attr('href'),
$tooltipContainer = $(href);
// if a container with the id was found
if ($tooltipContainer.length) {
// if the tooltip is not already active
if (!$tooltipContainer.hasClass('active')) {
$tipContent.removeClass('active');
$('.lhde__tooltip__content.opened').remove();
$tooltipContainer.addClass('active');
$clicked.append('<div class="lhde__tooltip__content opened">' + $tooltipContainer.html() + '</div>');
// hide the tooltip
} else {
$tipContent.removeClass('active');
$('.lhde__tooltip__content.opened').remove();
}
}
});
$(document).click(function(e){
if ($(e.target).not(':has(.lhde__tooltip)').length == 0 && $('div.opened').length) {
// current click target is not the tooltip and a tip is open
//console.log($('div.opened'));
$('div.opened').remove();
//$tipContent.removeClass('active');
}
});
})(jQuery);
.content {
width: 150px;
background: #eee;
color: #333;
margin: 50px auto;
}
a {
color: black;
text-decoration: none;
display: block;
margin: 20px 0;
position: relative;
padding: 20px;
text-align: center;
}
.lhde__tooltip__content {
position: absolute;
background: #333;
color: white;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"> <a class="lhde__tooltip" href="#kardiologen">Kardiologen</a>
<a class="lhde__tooltip" href="#pneumologen">Pneumologen</a>
</div>
<div class="lhde__tooltip__content" id="kardiologen">
<h3 class="lhde__third-headline">Kardiologen</h3>
<p class="lhde__paragraph">Lorem ipsum dollor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum soccis natoque penatabus et magais dis partiruent.</p> <span class="lhde__icon lhde__icon--close"></span>
</div>
<div class="lhde__tooltip__content" id="pneumologen">
<h3 class="lhde__third-headline">Pneumologen</h3>
<p class="lhde__paragraph">Lorem ipsum dollor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum soccis natoque penatabus et magais dis partiruent.</p> <span class="lhde__icon lhde__icon--close"></span>
</div>