JQuery、Js獲取元素、鼠標位置

單機某個元素彈出窗口有時需要動態的獲取元素的位置
例如:
這裏寫圖片描述
例如圖片中的彈框,如果紅色單詞向右移動,彈窗會顯示不完整
JQuery 獲得絕對,相對位置的座標方法

//獲取頁面某一元素的絕對X,Y座標
var X = $('#ID').offset().top;
var Y = $('#ID').offset().left;
//獲取相對(父元素)位置:
var X = $('#ID').position().top;
var Y = $('#ID').position().left;

還可以在發生事件時通過screenX、clientX、pageX獲取元素位置
screenX:鼠標位置相對於用戶屏幕水平偏移量,而screenY也就是垂直方向的,此時的參照點也就是原點是屏幕的左上角。

clientX:跟screenX相比就是將參照點改成了瀏覽器內容區域的左上角,該參照點會隨之滾動條的移動而移動。

pageX:參照點也是瀏覽器內容區域的左上角,但它不會隨着滾動條而變動

如圖(紅點就是鼠標當前位置)
這裏寫圖片描述

參考代碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        .div {
            text-align: center;
            font-size: 24px;
            height: 300px;
            width: 1300px;
            line-height: 300px;
            color: yellow;
        }

        #d1 {
            background-color: red;
        }

        #d2 {
            background-color: green;

        }

        #d3 {
            background-color: blue;
        }

        #d4 {
            position: absolute;
            background-color: yellow;
            height: 150px;
            width: 120px;
            top: 0;
        }
    </style>
    <script type="text/javascript">

        $(function () {

            window.onscroll = function () {
                $("#d4").css("top", getScrollTop());
            };

            document.onmousemove = function (e) {
                if (e == null) {
                    e = window.event;
                }
                var html = "screenX:" + e.screenX + "<br/>";
                html += "screenY:" + e.screenY + "<br/><br/>";
                html += "clientX:" + e.clientX + "<br/>";
                html += "clientY:" + e.clientY + "<br/><br/>";
                if (e.pageX == null) {
                    html += "pageX:" + e.x + "<br/>";
                    html += "pageY:" + e.y + "<br/>";
                } else {
                    html += "pageX:" + e.pageX + "<br/>";
                    html += "pageY:" + e.pageY + "<br/>";
                }

                $("#d4").html(html);
            };
        });

        function getScrollTop() {
            var top = (document.documentElement && document.documentElement.scrollTop) ||
              document.body.scrollTop;
            return top;
        }
    </script>
</head>
<body>
    <div id="d1" class="div">div1 height:300px width:1300px</div>
    <div id="d2" class="div">div2 height:300px width:1300px</div>
    <div id="d3" class="div">div3 height:300px width:1300px</div>
    <div id="d4"></div>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章