0

我有这个代码已经工作:

<div class="tippytrip">Here's a link!</div>
<div class="tippytrip">Here's a link!</div>
<div class="tippytrip">Here's a link!</div>
<div id="tooltip-container">The tooltip!</div>

$('.tippytrip').hover(function(){
    var offset = $(this).offset();
    console.log(offset)
    var width = $(this).outerWidth();
    $('#tooltip-container').css({top:offset.top, left:offset.left + width + 10}).show();
}, function(){
    $('#tooltip-container').hide();
});

.tippytrip {cursor:pointer; margin-bottom:40px; width:80px; border:2px solid #ccc; padding:5px}
#tooltip-container {position:absolute; padding:30px; background:black; color:white; display:none}

http://jsfiddle.net/5LSxG/

但它只适用于具有该 id 的一个工具提示容器,我希望它是动态的,无论是调用者还是被调用的 div。

4

1 回答 1

0

您可以使用数据属性使其动态化。

<div class="tippytrip" data-tip="Tip 1">Here's a link!</div>
<div class="tippytrip" data-tip="Tip 2">Here's a link!</div>
<div class="tippytrip" data-tip="Tip 3">Here's a link!</div>
<div id="tooltip-container">The tooltip!</div>

$('.tippytrip').hover(function(){
    var offset = $(this).offset();
    console.log(offset)
    var width = $(this).outerWidth();
    $('#tooltip-container').html($(this).data('tip')).css({top:offset.top, left:offset.left + width + 10}).show();
}, function(){
    $('#tooltip-container').hide();
});

.tippytrip {cursor:pointer; margin-bottom:40px; width:80px; border:2px solid #ccc; padding:5px}
#tooltip-container {position:absolute; padding:30px; background:black; color:white; display:none}

JSFiddle

如果您希望每个链接有多个提示容器,那么您可以执行以下操作:

<div class="tippytrip" data-tip="1">Here's a link!</div>
<div class="tippytrip" data-tip="2">Here's a link!</div>
<div class="tippytrip" data-tip="3">Here's a link!</div>
<div class="tooltip-container" id="tooltip-container1">First Tip</div>
<div class="tooltip-container" id="tooltip-container2">Second Tip</div>
<div class="tooltip-container" id="tooltip-container3">Third Tip</div>

$('.tippytrip').hover(function(){
    var offset = $(this).offset();
    console.log(offset)
    var width = $(this).outerWidth();
    $('#tooltip-container' + $(this).data('tip')).css({top:offset.top, left:offset.left + width + 10}).show();
}, function(){
    $('#tooltip-container' + $(this).data('tip')).hide();
});

.tippytrip {cursor:pointer; margin-bottom:40px; width:80px; border:2px solid #ccc; padding:5px}
.tooltip-container {position:absolute; padding:30px; background:black; color:white; display:none}

JSFiddle

于 2013-06-13T19:06:32.330 回答