迭代一组列表项时,无法使.offset()方法工作

时间:2011-11-16 21:42:19

标签: javascript jquery offset

基本上,我正在尝试在点击一组列表项时应用类似工具提示的弹出窗口。除了弹出窗口的定位外,一切似乎都运行正常。我正在尝试使用.offset()来获取每个列表项的坐标,以便我可以相对于列表项定位弹出div。我已经在下面包含了相关的html元素,css和我的脚本。任何帮助将非常感激!

HTML:

<ul>
    <li class="checked" title="This is a test popup message">Yada yada yada</li>
    <li class="checked" title="This is another test popup message">Yada yada yada</li>
    <li class="checked" title="This is yet another test popup message">Yada yada yada</li>
</ul>

CSS:

.popup {
    position: absolute;
    width: 300px;
    padding: 20px;
    background: rgba(0,0,0, .5);
    z-index: 10000;
    display: none;
}

JavaScript的:

$(document).ready(function() {

activatePopup = function() {
    var popupMarkup = '<div class="popup">' + '</div>';
    return popupMarkup;
}

$('body').prepend(activatePopup());

$('.checked').each(function() {
    // Sets popup text based on title attribute
    var popup = $('.popup');
    var popupText = $(this).attr('title');
    $(this).attr('title', '');

    //Grabs Position data of trigger element
    var pos = $(this).offset();
    var posTop = pos.top;
    var posLeft = pos.left;


    $(this).click(function() {
        popup.html(popupText);
        if (popup.is(":hidden")) {
            popup.fadeIn('fast');
        } else {
            popup.fadeOut('fast');
        }

        $(this).toggleClass('unchecked');
        $(this).toggleClass('checked');

        setPos(posTop, posLeft);
    });

    setPos = function(top, left) {
        var yPos = (top - 80) + 'px';
        var xPos = (left + 40) + 'px';

        popup.css({'top' : yPos, 'left' : xPos});
    }
});
});

1 个答案:

答案 0 :(得分:0)

尝试包括

//Grabs Position data of trigger element
var pos = $(this).offset();
var posTop = pos.top;
var posLeft = pos.left;

在你click内部的功能如下:

   $(this).click(function() {
        var pos = $(this).offset();
        var posTop = pos.top;
        var posLeft = pos.left;

        popup.html(popupText);
        if (popup.is(":hidden")) {
            popup.fadeIn('fast');
        } else {
            popup.fadeOut('fast');
        }

        $(this).toggleClass('unchecked');
        $(this).toggleClass('checked');

        setPos(posTop, posLeft);
    });

这应该这样做:)