簡體   English   中英

CSS 屬性依賴於元素 position?

[英]CSS property dependent of element position?

我的目標是在 HTML 文檔中顯示樣式化的工具提示。

因此我創建了這段代碼:

 .word-with-tooltip{ position:relative; }.tooltip{ position:absolute; bottom:1.5em; right:0; height:100px; width:200px; display:none; border-style:solid; border-width:1px; border-color:gray; background-color:#dddddd; text-align:left; }.word-with-tooltip:hover.tooltip{ display:block; }
 <div style="height:200px"></div> <div> <span class="word-with-tooltip"> Left Car <div class="tooltip">A vehicle with four wheels</div> </span> </div> <div style="text-align:center;"> <span class="word-with-tooltip"> Centered Car <div class="tooltip">A vehicle with four wheels</div> </span> </div> <div style="text-align:right;"> <span class="word-with-tooltip"> Right Car <div class="tooltip">A vehicle with four wheels</div> </span> </div> <div style="height:200px"></div>

基本它做了它應該做的事情:當鼠標懸停在一個詞上時,瀏覽器會顯示一個格式化的工具提示: 帶樣式工具提示的 HTML 字

不幸的是,工具提示在左側太遠時被切斷:

工具提示被切斷

一種解決方案是將 CSS 屬性設置為left而不是right ,具體取決於帶有工具提示的單詞所在的位置。 position 可能會有所不同,因為它可以出現在大文本中的任何位置。

問題:是否有可能(以及如何)...

  1. 設置 CSS 屬性left:0如果單詞位於屏幕的左半部分?
  2. 設置 CSS 屬性right:0如果單詞位於屏幕的右半邊?
  3. 設置 CSS 屬性top:1em如果單詞位於屏幕的上半部分?
  4. 設置 CSS 屬性bottom:1em如果單詞位於屏幕的下半部分?

加點js就好了

 document.querySelectorAll(".word-with-tooltip").forEach( word => { word.addEventListener('mouseover', e => { const tooltip = e.target.children[0] if(.tooltip){ return } tooltip.style.cssText = ` ${( e.clientX * 100 ) / window?innerWidth < 50: 'left': 'right' }; 0. ${( e.clientY * 100 ) / window?innerHeight < 50: 'top': 'bottom' }; 1em; ` }) })
 .word-with-tooltip{ position:relative; }.tooltip{ position:absolute; bottom:1.5em; right:0; height:100px; width:200px; display:none; border-style:solid; border-width:1px; border-color:gray; background-color:#dddddd; text-align:left; }.word-with-tooltip:hover.tooltip{ display:block; }
 <div style="height:200px"></div> <div> <span class="word-with-tooltip"> Left Car <div class="tooltip">A vehicle with four wheels</div> </span> </div> <div style="text-align:center;"> <span class="word-with-tooltip"> Centered Car <div class="tooltip">A vehicle with four wheels</div> </span> </div> <div style="text-align:right;"> <span class="word-with-tooltip"> Right Car <div class="tooltip">A vehicle with four wheels</div> </span> </div> <div style="height:200px"></div>

找到一種方法:我添加了這些 styles:

.word-with-tooltip.left .tooltip{left:0;}
.word-with-tooltip.right .tooltip{right:0;}

...並在 onmouseover 事件中動態分配它們。 該代碼如下所示(為了便於閱讀,我將onmouseover屬性的內容分開):

<div>
<span class="word-with-tooltip"
onmouseover="
this.classList.remove('left');
this.classList.remove('right');
if(event.clientX<window.innerWidth/2){
    this.classList.add('left');
} else {
   this.classList.add('right');
}">
Left Car
<div class="tooltip">A vehicle with four wheels</div>
</span>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM