这是一个带有一种可能解决方案的 jsFiddle 。我正在使用 jQuery 的.hover()
方法为表格外的元素设置动画,并用表格内包含的内容填充它。这样,您的弹出元素就不会限制在表格的范围内。
这是jQuery代码:
$(function() {
$(".hover_over").hover( function() {
hovDiv = $(this);
showDiv = $(".show_hover");
showDiv.html(hovDiv.children("div").html());
showDiv.css("top", hovDiv.offset().top)
showDiv.css("left", hovDiv.offset().left + hovDiv.width()).show();
}, function() {
$(".show_hover").hide();
});
});
和 HTML:
<div class="theTable">
<div class="hover_over">1
<div>I'm hidden! 1</div>
</div>
<div class="hover_over">2
<div>I'm hidden! 2</div>
</div>
<div class="hover_over">3
<div>I'm hidden! 3</div>
</div>
<div class="hover_over">4
<div>I'm hidden! 4</div>
</div>
<div class="hover_over">5
<div>I'm hidden! 5</div>
</div>
</div>
<div class="show_hover"></div>
和CSS:
.show_hover {
display:none;
position:absolute;
background-color:black;
width:100px;
height:20px;
font-size:14px;
color:white;
}
.hover_over div { display:none; }
更新
因为你问了,所以我决定用纯 JavaScript 来完成这项工作。它不是那么容易阅读,但同样的想法适用:将弹出 div 移到表格之外,并使用onmouseover
事件onmouseout
处理程序动态添加所需的内容和定位。
这是新的 jsFiddle。
这是相关的代码:
Javascript
(function() {
function hoverIn() {
var hovDiv = this;
var showDiv = document.getElementById("show_hover");
showDiv.innerHTML = hovDiv.children[0].innerHTML;
showDiv.className = "see";
var newTop = hovDiv.offsetTop + hovDiv.offsetParent.offsetTop + hovDiv.offsetParent.offsetParent.offsetTop;
showDiv.style.top = "" + newTop + "px";
var newLeft = hovDiv.offsetLeft + hovDiv.offsetParent.offsetLeft + hovDiv.offsetParent.offsetParent.offsetLeft + hovDiv.clientWidth;
showDiv.style.left = "" + newLeft + "px";
};
function hoverOut() {
document.getElementById("show_hover").className = "";
};
var hoverDivs = document.getElementsByClassName("hoverdiv");
for(var i = 0; i < hoverDivs.length; i++)
{
hoverDivs[i].onmouseover = hoverIn;
hoverDivs[i].onmouseout = hoverOut;
}
})();
CSS
#show_hover
{
display:none;
position:absolute;
top:0;
left:0;
}
#show_hover.see {
display:block;
background-color:green;
width:400px;
height:80px;
position:absolute;
top:20px;
left:20px;
}
更新 2
这个答案越来越长。这是新的 jsFiddle。此更新允许您将鼠标悬停在显示的 div 上以与里面的对象进行交互。我利用了hoverIntent jQuery 插件背后的基本思想,即将onmouseout
处理程序放在一个setTimeout
调用后面,允许您在半秒内将鼠标移到弹出窗口中,然后它就会消失。这有点烦躁,所以你可能会玩等待时间,直到它完成你想要的。
此外,如果您只想检查鼠标在任何给定时刻的位置并触发显示/隐藏行为,请参阅此 StackOverflow 问题。
也就是说,这是更新的重要部分:
var mouseInShowHover = false;
var showDiv = document.getElementById("show_hover");
showDiv.onmouseover = function() { mouseInShowHover = true; }
showDiv.onmouseout = function() {
mouseInShowHover = false;
showDiv.className = "";
}
function hoverOut() {
setTimeout( function() {
if( !mouseInShowHover )
showDiv.className = "";
}, 500);
};