【问题标题】:Positioning top of element relative to table cell when position is absolute当位置为绝对时,相对于表格单元格定位元素的顶部
【发布时间】:2019-12-18 04:37:37
【问题描述】:

请在此处访问我的网站:

http://35.232.230.0:81/

您会看到一个目录项目表。将鼠标悬停在其中一张图像上。您应该会看到图片放大了。

您可能还会注意到图像有点闪烁。当您将鼠标悬停在缩略图的上部时会发生这种情况。

发生这种情况的原因是,您会注意到,放大图像的上边缘位于缩略图图像的中间附近。这意味着当图像放大时,鼠标位于放大图像的正上方。这意味着,只要您移动鼠标,它就会将其检测为 mouseout 事件,这会导致图像再次缩小。但这反过来又会触发放大,因为鼠标仍然悬停在缩略图上。这个结果是一个放大和缩小的循环,当你看到它非常快时,会给你闪烁。

所以我想知道是否有办法强制放大图像的顶部与缩略图图像相同。

悬停事件导致 css 转换,其中要转换的类将图像的位置设置为绝对位置:

img {
    transition: width 0;

    &:hover {
        position: absolute;
        z-index: 100;
        width: 300px;
        border: 1px solid black;
        box-shadow: 5px 5px 10px grey;

        transition: width .2s linear;
    }
}

我会尝试通过将放大图像的 top 属性设置为 0 来调整它,但是使用 position: absolute,这只会导致图像位于屏幕的左上角。我不确定如何计算 CSS 中相对于其包含元素的位置(角度垫表中的 td),所以我不知道如何做到这一点。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: css position transition absolute mat-table


    【解决方案1】:

    首先,要使position: absolute 达到您想要的效果,您需要定位与其相关的父对象(任何不是position: static 的对象)。

    这意味着在包含<td> 上设置position: relative 应该 工作。但很可惜,事实并非如此。 :( That is because relative position on table cells is undefined 并且大多数浏览器都不能很好地处理它。太糟糕了。

    所以,最好的办法是用<div>(或类似的东西)和position: relative 来包装你的图像,如下例所示。

    table {
      border-collapse: collapse;
    }
    
    table th,
    table td {
      padding: 5px;
    }
    
    table td {
      border-top: 1px solid;
    }
    
    div {
      height: 100px;
      position: relative;
      width: 100px;
    }
    
    img {
      border: 1px solid transparent;
      height: auto;
      position: absolute;
      transition: width .2s linear;
      width: 100px;
      z-index: 100;
    }
    
    img:hover {
      border-color: #000;
      box-shadow: 5px 5px 10px grey;
      width: 400px;
      z-index: 110;
    }
    
            
    <table>
      <tr>
        <th>Name</th>
        <th>Image</th>
        <th>Description</th>
      </tr>
      <tr>
        <td>Name</td>
        <td>
          <div>
            <img src="https://dummyimage.com/400x400/f48224/fff" alt>
          </div>
        </td>
        <td>Description</td>
      </tr>
      <tr>
        <td>Name</td>
        <td>
          <div>
            <img src="https://dummyimage.com/400x400/f48224/fff" alt>
          </div>
        </td>
        <td>Description</td>
      </tr>
      <tr>
        <td>Name</td>
        <td>
          <div>
            <img src="https://dummyimage.com/400x400/f48224/fff" alt>
          </div>
        </td>
        <td>Description</td>
      </tr>
    </table>

    另一个解决方案可能是使用 CSS 转换 (scale),因为这些转换不会改变元素的文档流。

    【讨论】:

    • 太棒了!该解决方案奏效了。谢谢 maryisdead。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多