javascript - 如何在表行 (tr) 上叠加一个 div(或任何元素)?

标签 javascript jquery html css overlay

我想在恰好有不止一列的表格行(tr 标签)上覆盖一个 div(或任何可用的元素)。

我试了几种方法,好像都不行。我在下面发布了我当前的代码。

我确实得到了一个叠加层,但不是直接覆盖在行上。我尝试将叠加顶部设置为 $divBottom.css('top'),但它始终是“自动”。

那么,我是否在正确的轨道上,或者有更好的方法吗?如您所见,使用 jQuery 很好。

如果我在正确的轨道上,我该如何正确放置 div? offsetTop 是包含元素、表中的偏移量,我需要做一些数学运算吗?我还会遇到其他问题吗?

$(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>

最佳答案

你需要让overlay div有一个绝对位置。还对行的顶部和左侧位置使用 position() jQuery 方法 - 这里是缺少的部分:

var rowPos = $divBottom.position();
bottomTop = rowPos.top;
bottomLeft = rowPos.left;

//
$divOverlay.css({
    position: 'absolute',
    top: bottomTop,
    left: bottomLeft,
    width: bottomWidth,
    height: bottomHeight
});

关于javascript - 如何在表行 (tr) 上叠加一个 div(或任何元素)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3065080/

相关文章:

html - 以编程方式检查是否使用了 CSS 文件

javascript - 如何在gulp中复制静态html页面

javascript - 使用 setinterval 不断点击 id

javascript - 是否可以在当前选项卡中模拟隐身模式? ( Chrome 扩展)

javascript - Javascript 中的正则表达式 : replace minus with comma+minus when condition is met

javascript - 尝试使用 formvalidator.net 为 "alpha"编写自定义验证器?

javascript - 当字符串中只有一个元素时,如何在 jQuery 中将字符串拆分为数组?

javascript - 在 html 元素上使用 jQuery ReplaceWith

jquery - 具有可变宽度子元素的CSS3/无限垂直滚动轮播

javascript - 如果选中一个单选按钮则隐藏