jQuery - 点击项目的位置

时间:2013-08-11 10:38:30

标签: jquery position

在我使用以下代码的脚本中用于在屏幕中间放置一个弹出窗口。

我需要以Y位置与我点击的项目相同的方式更改此设置。因此,如果我点击一个项目,弹出窗口应显示在与我单击的项目相同的高度。我不知道jquery和2小时的尝试没有帮助。任何帮助赞赏

我标记了需要编辑的行。

                switch(a)
            {
                case 'postdetails':
                case 'userdetails':
                    $('#reputation-popup').addClass('normal-popup');
                    targetleft = ($(window).width() - $('#reputation-popup').outerWidth()) / 2;
                    targettop = ($(window).height() - $('#reputation-popup').outerHeight()) / 2;
                    /////// THE LINE ABOVE THIS IS THE ONE I NEED TO EDIT!!!! //////////

                break;
                case 'newpopup':
                    $('#reputation-popup').addClass('new-popup');
                    targetleft = ($(window).width() - $('#reputation-popup').outerWidth()) / 2;
                    targettop = ($(window).height() - $('#reputation-popup').outerHeight()) / 2;
                break;
                default:
                    $('#reputation-popup').addClass('small-popup');
                    // Center popup relative to clicked coordinate
                    targetleft = c.pageX - $('#reputation-popup').outerWidth() / 2;
                    // Popup can not be too close or behind the right border of the screen
                    targetleft = Math.min (targetleft, $(document).width() - 20 - $('#reputation-popup').outerWidth());
                    targetleft = Math.max (targetleft, 20);
                    targettop = c.pageY + 10;
                break;
            }

3 个答案:

答案 0 :(得分:2)

$('#item1').click(function(){
     // GETS POSITION OF CLICKED ITEM
     var offset = this.offset();
     var x = offset.left;
     var y = offset.top;
     // GETS THE DIMENSION OF THE CLICKED ITEM
     var w = this.width();
     var h = this.height();
     // APPLY THE SETTINGS TO ITEM2 USING CSS FUNCTION
     $('#item2').css({
         .....
     });
    // http://api.jquery.com/css/

});

答案 1 :(得分:1)

尝试:

 $("item").offset().top;
 $("item").offset().left;

此处有更多信息:http://api.jquery.com/offset/

答案 2 :(得分:1)

您可以使用以下jQuery函数来定位弹出菜单:

1)event.pageX,event.pageY为您提供相对于文档的鼠标位置

参考:http://api.jquery.com/event.pageY/

2)offset():它给出元素的偏移位置

参考:http://api.jquery.com/offset/

3)position():它给出了元素的相对位置

参考:http://api.jquery.com/position/