如何在HTML中實現元素的層疊效果?
P粉486138196
P粉486138196 2023-08-28 16:39:50
0
2
416
<p>我想為這個元素製作一個自訂的工具提示,但是它被包含在一個框中,這個框沒有足夠的空間來顯示工具提示,所以它只是被裁剪了(實際上我可以滾動來顯示它,因為<code>overflow</code>被設定為<code>auto</code>,但我希望它能夠在不滾動的情況下可見)。有沒有辦法讓它超出邊界顯示?我嘗試過使用<code>z-index</code>但沒有效果。 </p> <p>這就是我所說的:</p> <p> <pre class="brush:css;toolbar:false;">.box { width: 100px; height: 100px; overflow: auto; border-style: solid; border-color: red; } .tooltip { padding-top: 20px; position: relative; display: inline-block; } .tooltip .tooltiptext { display: none; max-width: 60vw; min-width: 15vw; background-color: white; border-style: solid; border-color: #1a7bd9; position: absolute; z-index: 1000000; } .tooltip:hover .tooltiptext { display: block; }</pre> <pre class="brush:html;toolbar:false;"><div class='box'> <div class='tooltip'> 滑鼠懸停顯示工具提示 <div class='tooltiptext'> 哇,這太棒了,這是一個史詩級的工具提示文本 </div> </div> </div></pre> </p> <p>編輯:重要的是懸停在元素上有效,而不是它所在的框框上。 </p>
P粉486138196
P粉486138196

全部回覆(2)
P粉982881583

有很多方法可以實現,但如果你只是想讓工具提示在容器外可見,你不需要使用z-indexoverflow。你只需要將工具提示移到相對容器內的定位上下文。

根據你的評論,由於你希望工具提示只在懸停在文本上時出現,我建議你的相對容器精確地包裹住你想懸停的內容。為了說明這一點,我在外框上添加了一個邊框,與你決定使用相對容器的位置相比。

然後,只需將box:hover更改為relative-container:hover以定位到正確的元素。

我試圖組織HTML和類別名,使其更具語義性和簡潔性以進行說明。希望對你有幫助!

範例

.box {
  padding: 30px;
  border: blue solid;
  width: 300px;
  display: flex;
  align-items: center;
}

.relative-container {
  position: relative;
}

.box-content {
  border-style: solid;
  border-color: red;
  padding: 10px;
}

.tooltip {
  position: absolute;
  left: 0;
  top: 0;
  max-width: 60vw;
  min-width: 15vw;
  background-color: white;
  border: #1a7bd9 solid;
  display: none;
}

.relative-container:hover .tooltip {
  display: block;
  cursor: pointer;
}
<div class='box'>
  <div class='relative-container'>
    <div class='box-content'>
      Hover for tooltip. I have a little padding to give the text some room.
    </div>
    <div class='tooltip'>
    Wow, this is amazing, such an epic tooltip text. I'm aligned with the top of the box content containing text and take up the full width. I only appear when hovering over the box content (red outline), not the surrounding container (blue outline).
    </div>
  </div>
</div>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!