jQuery创建页面“map-overview”

时间:2012-12-18 21:16:36

标签: jquery offset dimensions jquery-calculation

我尝试创建一个“页面'地图' - 概述”like this(或者甚至更复杂like this)但是我坚持计算,不知道问题可以在何处或如何消除。

目前为止what I've done

var Overview = (function() {

    $('.spot').each(function() {
        var el = $(this),
            map = $('#map'),
            point = document.createElement('span');

        point.className = 'point';
        map.append(point);

        var offsetX = el.offset().left, // Might the problem is here,
            offsetY = el.offset().top, // and here?!
            winW = $(window).width(),
            winH = $(window).height(),

            mapWidth = map.width() - $(point).width(),
            mapHeight = map.height() - $(point).height(),

            posX = offsetX / winW * mapWidth,
            posY = offsetY / winH * mapHeight;

        $(point).css({
            top: posY,
            left: posX
        });
    });

})();

我无法弄清楚问题出在哪里。任何想法如何修复或改进我的计算?

1 个答案:

答案 0 :(得分:1)

好的,我自己fixed it。也许它可以帮助别人:

var Overview = function() {
    $('body').append('<div class="minimapWrapper"><div class="miniMap"><i class="cursor"></i></div></div>');

    var holder = $("#holder"),
        miniMap = $(".miniMap"),
        spots = holder.find('.spot'),
        holderPos = holder.offset();

    if (spots.length > 0) {
        var holderW = holder.width(),
            holderH = holder.height(),
            mapW = miniMap.width(),
            mapH = miniMap.height();

        spots.each(function() {
            var point = $(this),
                pointPos = point.offset(),
                top = pointPos.top - holderPos.top,
                left = pointPos.left - holderPos.left,

                marker = $(document.createElement('span')),
                markerTop = (mapH * top) / holderH,
                markerLeft = (mapW * left) / holderW;

            markerTop = Math.abs(markerTop);
            markerLeft = Math.abs(markerLeft);

            marker.css({
                top: markerTop,
                left: markerLeft
            })[0].className = 'marker';

            miniMap.append(marker);

            marker.click(function() {
                $('html,body').animate({
                    scrollTop: pointPos.top,
                    scrollLeft: pointPos.left
                });
                return false;
            });
        });
    }
};