DIV CSS 佈局教程網

jQuery 實現跟隨鼠標移動的提示框效果
編輯:JQuery特效代碼     

提示框是網頁中常見的交互元素。本文分享一個基於 jQuery 的鼠標跟隨提示框效果:當鼠標移入鏈接時,會在光標旁邊彈出一個顯示提示文字的小框,並隨鼠標移動而移動;此外還提供了頁面居中顯示的變體。

效果體驗:https://hovertree.com/texiao/jsstudy/2/

實現思路

整體分為三個關鍵步驟:

  1. 鼠標移入標題時(這裡是 <a> 標簽):創建一個 div,內容為提示文本,將其加入文檔,並根據鼠標位置設置提示層的位置後顯示。
  2. 鼠標移出標題時:移除該 div。
  3. 鼠標在標題內移動時:實時更新 div 的位置,實現跟隨效果。

跟隨光標的完整代碼

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery彈出光標跟隨提示框 - 何問起</title>
<style type="text/css">
#tooltip {
    position: absolute;
    border: #333 1PX solid;
    background: #f7f5d1;
    padding: 1px;
    color: #333;
    display: none;
}
a { color: blue; }
#hovertree, #yestop, #hoverclock { width: 789px; margin: 20px auto; }
</style>
<script src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="hovertree">
<a href="https://hovertree.com" class="tooltip" title="何問起首頁">何問起首頁</a>
<a href="https://hovertree.com/texiao/" class="tooltip" title="網頁特效庫">特效</a>
</div>
<div id="yestop">
<a href="https://hovertree.com/h/bjaf/tishikuang.htm" class="tooltip" title="本效果代碼">原文</a>
<a href="https://hovertree.com/texiao/jsstudy/2/" class="tooltip" title="本效果網址">效果</a>
<a href="#" class="tooltip" title="彈出層">test</a>
</div>
<div id="hoverclock">請把光標在各個鏈接上面移動,將會彈出跟隨光標的提示框。</div>
<script>
$(function () {
    var x = 15;
    var y = 10;
    $("a.tooltip").mouseover(function (e) { // 當鼠標指針從元素上移入時
        this.myTitle = this.title;
        this.title = "";
        var tooltip = "<div id='tooltip'>" + this.myTitle + "</div>";
        $("body").append(tooltip);
        $("#tooltip").css({ "top": (e.pageY + y) + "px", "left": (e.pageX + x) + "px" }).show("fast");
    }).mouseout(function () { // 當鼠標指針從元素上移開時
        this.title = this.myTitle;
        $("#tooltip").remove();
    }).mousemove(function (e) { // 當鼠標指針在元素上移動時
        $("#tooltip").css({ "top": (e.pageY + y) + "px", "left": (e.pageX + x) + "px" });
    });
});
</script>
</body>
</html>

頁面居中的變體

如果希望提示框固定在頁面某個位置而非跟隨鼠標,可以去掉 mousemove 中的坐標更新邏輯,改用固定的定位方式。居中效果演示地址:https://hovertree.com/texiao/jsstudy/2/1.htm 。

通過 this.myTitle 暫存原始 title、動態創建與移除 tooltip 元素,再配合 pageX/pageY 獲取鼠標坐標,就能實現流暢自然的跟隨提示效果。這段代碼邏輯清晰、易於定製,可靈活應用到表單提示、圖標說明等場景中。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved