使用jQuery无法正确定位弹出窗口

时间:2015-06-08 21:10:06

标签: jquery

我使用e.pageX / e.pageY让我的弹出窗口工作,但后来我注意到如果我点击页面右侧或底部附近的某些内容,弹出窗口就会离开页面。我read关于使用位置以及它将如何自动调整,但我必须有错误。有人可以帮我定位我的弹出窗口并在页面打开时将其保留在页面上吗?

这是fiddle,说明了我要做的事情。

var hoverTimer;

var mouseOverText = "This is normally a looked up value. Hard-coded here so
I can illustrate the problem. I'd like the popup to show up to the right
 bottom of the mouse unless near the right or bottom of the page. I thought
 position automatically did that."

$(".lookup").hover(
    function (e) {
        hoverTimer = setTimeout(function () {
            showPopupText(e, mouseOverText, "#4aacc5");
        }, 100); // Changed wait time for fiddle.
    },

    function (e) {    // Supposed to clear the popup when the mouse moves
    away. Works on my laptop...not sure why not in fiddle, so not concerned
    about this.
        clearTimeout(hoverTimer);
});

function showPopupText(e, mouseOverText, bkgColor) {
    var html = '<div id="titlePopup" class="tooltip info" 
        style="background-color:' + bkgColor + '; ' + 'display: block;">' 
        + '<span id="temp">' + mouseOverText + '</span>' + '</div>';

    timerPopup = setTimeout(function () {
        $('div#titlePopup').remove();

        $('body').append(html);

        var htmlPopup = $("#titlePopup");

        $(htmlPopup).position({
            my: "right bottom",
            at: "right bottom",
            of: "event"  // Tried different values...none seem to work.
        });

    }, 100);
}

1 个答案:

答案 0 :(得分:0)

您可以在页面上使用display: none;属性设置块元素。然后在你的jquery函数

$(".lookup").hover(function(){
    $("#yourBlockId").toggle();
}, function(){
   $("#yourBlockId").toggle();
})

至于把你的街区放在哪里,我会建议你想要它的地方

<div style="position: relative; width: 100%;">
    <div id="yourBlockId" style="position: absolute; right: 0; display: none;">BLOCK CONTENT</div>
</div>

编辑:忘记在块元素上添加display: none

EDIT2:好的我觉得我现在正在做你想做的事情,我认为你需要先计算你的元素的宽度和高度。像这样:

$(".lookup").hover(function(event){
    block = $("#titlePopup");
    height = block.height();
    width = block.width();
    maxHeight = $(window).height();
    maxWidth = $(window).width();
    posX = event.pageX;
    posY = event.pageY;
    if ((event.pageX + width) >= maxWidth)
        posX = maxWidth - width; //you can substract a little more just in case
    if ((event.pageY + height) >= maxHeight)
        posY = maxHeight - heigth;
    //Now you have the position where your element goes. You can continue with what you had
})