當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


jQuery event.relatedTarget用法及代碼示例


jQuery event.relatedTarget是一個內置屬性,用於查找鼠標移動時正在進入或退出的元素。

用法:

event.relatedTarget

參數:它不接受任何參數,因為它是屬性而不是函數。

示例 1:此示例顯示event.relatedTarget 屬性的工作原理。

HTML


<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <!--jQuery code to show working of this property-->
    <script> 
            $(document).ready(function () { 
                $("div, p").mouseenter(function (event) { 
                    $("#d2").html("Pointer at : "  
                        + event.relatedTarget.nodeName); 
                }); 
            }); 
    </script> 
    <style> 
        #d1 { 
            height: 100px; 
            width: 50%; 
            padding: 10px; 
            border: 2px solid green; 
        } 
  
        #d2 { 
            height: 20px; 
            width: 50%; 
            padding: 10px; 
            margin-top: 10px; 
            border: 2px solid green; 
        } 
    </style> 
</head> 
  
<body> 
    <!-- this is outer div element -->
    <div id="d1"> 
        <!-- this is inner div element -->
        <div>This is a div element </div> 
        <!-- this is paragraph element -->
        <p style="background-color:lightgreen"> 
            This is a paragraph 
        </p> 
    </div> 
    <div id="d2"></div> 
</body> 
  
</html>

輸出:

示例 2:在此示例中,當鼠標從元素退出時,將顯示一個彈出窗口。

HTML


<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <!--jQuery code to show working of this property-->
    <script> 
            $(document).ready(function () { 
                $("div, p").mouseenter(function (event) { 
                    $(this).animate({ fontSize: "+=14px"}); 
                }); 
                $("div, p").mouseleave(function (event) { 
                    $(this).animate({ fontSize: "-=14px"}); 
                    alert("Pointer at : "  
                        + event.relatedTarget.nodeName); 
                }); 
            }); 
    </script> 
    <style> 
        #d1, #d2 { 
            background-color: lightgreen; 
            height: 30px; 
            width: 50%; 
            padding: 10px; 
            margin-top: 10px; 
            border: 2px solid green; 
        } 
    </style> 
</head> 
  
<body> 
    <div id="d1"> 
        Geeksforgeeks 
    </div> 
    <p id="d2"> 
        A computer science portal 
    </p> 
</body> 
  
</html>

輸出:



相關用法


注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery event.relatedTarget Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。