问题
I want to show an overlay div sitting on top of the hovered div similar to this effect on IBM website: http://www.ibm.com/us/en/
Please look at the 3 boxes near the footer. Hover on the box "Let's build a smarter planet" to view the effect.
回答1:
I've created a working example. Basically you need to create 3 divs with a visible and the invisible containers, add hover event handler and toggle the tooltip's visibility in that handler.
HTML:
<div class="parents">
<div class="box type-1">box 1</div>
<div class="tooltip type-1">tooltip 1</div>
</div>
<div class="parents">
<div class="box type-2">box 2</div>
<div class="tooltip type-2">tooltip 2</div>
</div>
<div class="parents">
<div class="box type-3">box 3</div>
<div class="tooltip type-3">tooltip 3</div>
</div>
CSS:
.parents
{
float: left;
margin: 5px;
}
.box,
.tooltip
{
width: 80px;
height: 30px;
line-height: 30px;
background-color: #666;
color: #fff;
border: 1px solid #222;
text-align: center;
}
.tooltip
{
display: none;
position: absolute;
top: 50px;
}
jQuery code:
$(document).ready
(
function ()
{
// add hover event handler
$('.box').hover
(
function ()
{
// find the triggering box parent, and it's tooltip child
$(this).parent().children('.tooltip').animate
(
{
opacity: "toggle", // toggle opacity
}
);
}
);
}
);
回答2:
IBM is using Dojo's .expand method. You can do the same functionality in jQuery using the expand plugin.
回答3:
You can easily do that. The steps should follow:
1) Have 3 blocks like DIVs or UL LIs and add the hidden container inside(or it doesn't matter if you will set the position with jQuery. If your structure would be:
<div class="block">
<div class="invisible"></div>
<div class="visible"></div>
</div>
2) Attach mouseenter and mouseleave events to all 3 blocks like:
$('.block').mouseenter(function() {
// some code to show the hidden container
$(this).find('.visible').show().addClass('visible_container');
});
$('.block').mouseleave(function() {
// some other code to hide the shown container
$('.visible_container').hide(); // Hide all the instances of .visible_container
});
3) You should modify JS or CSS according to the position methods for your elements so when show()
is called the element would be displayed right on top of the element. For example if you hidden block would have a CSS rule position: absolute
you would use:
$(this).find('.visible')
.show()
.addClass('visible_container')
.css('top', $(this).offset().top+'px')
.css('left', $(this).offset().left+'px');
In this case the shown container would be adjusted to the right upper corner of the hovered block.
As the hidden container is a child of the block container - no mouseleave event would be called so it would stay nicely displayed.
来源:https://stackoverflow.com/questions/7884674/how-to-show-an-overlay-div-when-hover-on-a-div-with-jquery