2011/12/06

跟隨鼠標的浮動視窗

要做出一個浮動視窗很簡單,但要加上判斷現在邊界在哪邊來因應相對位置就要下點功夫了,除了要抓出目前點選物件跟視窗的相對位置,還要加上對卷軸距離的判斷,否則就會出現像下圖的情況。

float div with cursor

Chrome Firefox IE Opera Safari

<!DOCTYPE HTML>
<html>
<head>
    <meta charset=utf-8">
    <title>Cursor</title>
    <style type="text/css" media="screen">
    #floatdiv {
        position: absolute;
        top: 0;
        left: 0;
        border: 1px solid;
        width: 200px;
        height: 50px;
        display: none;
        background: #FFFF00;
        z-index: 100;
    }
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
    <script type="text/javascript">
        $(function() {
            var $div = $('#floatdiv');

            $('[name="btn"]').click(function(e) {
                var $wH = $(window).height(),
                    $sT = $(window).scrollTop(),
                    $pT = $(this).position().top,
                    $dH = $div.height(),
                    $eY = e.pageY,
                    $wW = $(window).width(),
                    $sL = $(window).scrollLeft(),
                    $pL = $(this).position().left,
                    $dW = $div.width(),
                    $eX = e.pageX;

                $top = ($wH-$pT+$sT < $dH) ? ($eY-$dH) : $eY; 
                $left = ($wW-$pL+$sL < $dW) ? ($eX-$dW) : $eX; 

                $div
                    .css({left: $left, top: $top})
                    .show();
                return false;
            });

            $div.click(function(e) {
                // 點擊 div 本身不觸動消失
                e.stopPropagation();
            });

            $(document).click(function() {
                // 點擊任一物件使 div 消失
                $div.hide();
            });
        });
    </script>
</head>
<body>
    <div id="floatdiv"></div>
    <a href="#" name="btn">click me</a>
</body>
</html>

1 則留言:

Eden 提到...

非常實用!