如何在表行(tr)上覆盖div(或任何元素)? [英] How to overlay a div (or any element) over a table row (tr)?
问题描述
我想在表格行(tr标记)上覆盖一个有多个列的div(或任何可以工作的元素)。
I'd like to overlay a div (or any element that'll work) over a table row (tr tag) that happens to have more than one column.
我试过几种方法,似乎不工作。我已经张贴我当前的代码下面。
I have tried a few methods, which don't seem to work. I've posted my current code below.
我收到一个覆盖,但不是直接在行上。我尝试将覆盖顶部设置为$ divBottom.css('top'),但它总是'auto'。
I do get an overlay, but not directly over just the row. I tried setting the overlay top to $divBottom.css('top'), but that is always 'auto'.
所以,我在正确的轨道,有没有更好的办法呢?使用jQuery是很好的,你可以看到。
So, am I on the right track, or is there a better way of doing it? Utilizing jQuery is fine as you can see.
如果我在正确的轨道,我如何得到正确放置div?是offsetTop在包含元素,表中的偏移量,我需要做一些数学?
If I am on the right track, how do I get the div placed correctly? Is the offsetTop an offset in the containing element, the table, and I need to do some math? Any other gotchas I'll run into with that?
$(document).ready(function() {
$('#lnkDoIt').click(function() {
var $divBottom = $('#rowBottom');
var $divOverlay = $('#divOverlay');
var bottomTop = $divBottom.attr('offsetTop');
var bottomLeft = $divBottom.attr('offsetLeft');
var bottomWidth = $divBottom.css('width');
var bottomHeight = $divBottom.css('height');
$divOverlay.css('top', bottomTop);
$divOverlay.css('left', bottomLeft);
$divOverlay.css('width', bottomWidth);
$divOverlay.css('height', bottomHeight);
$('#info').text('Top: ' + bottomTop + ' Left: ' + bottomLeft);
});
});
#rowBottom { outline:red solid 2px }
#divBottom { margin:1em; font-size:xx-large; position:relative; }
#divOverlay { background-color:Silver; text-align:center; position:absolute; z-index:10000; opacity:0.5; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Overlay Tests</title>
</head>
<body>
<p align="center"><a id="lnkDoIt" href="#">Do it!</a></p>
<table width="100%" border="0" cellpadding="10" cellspacing="3" style="position:relative">
<tr>
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></td>
</tr>
<tr id="rowBottom">
<td><div id="divBottom"><p align="center">This is the bottom text</p></div></td>
</tr>
<tr>
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></td>
</tr>
</table>
<div id="divOverlay" style=""><p>This is the overlay div.</p><p id="info"></p></div>
</body>
</html>
推荐答案
您需要使重叠div具有绝对位置。还可以使用position()jQuery方法为该行的顶部和左侧位置 - 这里是缺少的部分:
You need to make the overlay div have an absolute position. Also use the position() jQuery method for top and left positions of the row - here are the missing pieces:
var rowPos = $divBottom.position();
bottomTop = rowPos.top;
bottomLeft = rowPos.left;
//
$divOverlay.css({
position: 'absolute',
top: bottomTop,
left: bottomLeft,
width: bottomWidth,
height: bottomHeight
});
这篇关于如何在表行(tr)上覆盖div(或任何元素)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!