考慮一個帶有標籤和輸入欄位的div 元素:
<div> <label>Name</label> <input type="text"> </div>
如何建立當使用者將滑鼠懸停在div元素上時出現的工具提示,並帶有微妙的提示淡入/淡出效果?
對於顯示靜態訊息的基本工具提示,您可以使用title 屬性:
<div title="This is my tooltip"> <p>但是,對於具有動態文字和動畫淡入淡出效果的工具提示,需要更進階的方法:</p> <ol> <li>建立CSS動畫</li> <li>新增一個 JS 事件監聽器來處理懸停事件。 </li> <li>建立一個工具提示 DOM 元素並將其相對於 div 定位。 </li> <li>新增/刪除透過在懸停/移除懸停時套用 CSS 動畫來顯示工具提示。 </li> </ol> <p>這裡有一個使用 JavaScript 和CSS:</p> <pre class="brush:php;toolbar:false">.tooltip { display: none; position: absolute; padding: 10px; color: white; border: 1px solid black; opacity: 0; transition: all 0.2s; } .tooltip.show { display: block; opacity: 1; }
// Create a tooltip element const tooltip = document.createElement('span'); tooltip.classList.add('tooltip'); // Add the event listener to the div const div = document.querySelector('div'); div.addEventListener('mouseover', (e) => { // Set the tooltip text tooltip.textContent = 'This is my tooltip'; // Position the tooltip tooltip.style.left = e.x + 'px'; tooltip.style.top = e.y + 'px'; // Add the tooltip to the body document.body.appendChild(tooltip); // Add the show class to the tooltip tooltip.classList.add('show'); }); div.addEventListener('mouseout', () => { // Remove the tooltip from the body document.body.removeChild(tooltip); });
以上是如何為 Div 元素建立具有淡入/淡出效果的動態工具提示?的詳細內容。更多資訊請關注PHP中文網其他相關文章!