没有绝对值的弹出按钮

时间:2012-11-13 18:39:00

标签: javascript jquery html css

我已关注此post,以便创建一个类似于dropbox登录按钮的按钮。

更具体地说,这是我正在使用的代码:

echo '<a href="#" id ="loginbutton"></a>';

    echo '<div id = "popup">';
    echo '<div id = "popupimage"> </div>';

//HTML INSIDE POPUP

    echo '</div>';

    echo '<script type="text/javascript" src="jquery.js"></script>';
    echo '<script>';

    echo '$("#loginbutton").click(function(e){';
    echo '$("#popup").css("visibility","visible");';
    echo 'e.stopPropagation();';
    echo '});';

    echo '$("#popup").click(function(e){';
    echo 'e.stopPropagation();';
    echo '});';

    echo '$("body").click(function(e){';
    echo '$("#popup") . css("visibility", "hidden");';
    echo '});';

CSS:

#logbutton{
    top:50px;
    left:850px;
    position: absolute;
    background-image: url(../images/buttons/loginbutton.png);
    width:59px; 
    height:28px;   
}

#popupimage{
    top:63px;
    left:887px;
    position: absolute;
    background-image: url(../images/popupimage.png);
    visibility: hidden;
    width:400px; 
    height:600px;   
}

按钮有效,弹出窗口也会出现。

弹出图像的CSS指定图像将出现的绝对位置,这就是导致问题的原因。我现在希望在按钮之前添加一些动态内容,因此我无法确定按钮的位置。这导致弹出图像没有放在按钮附近。

是否可以知道按钮的绝对位置,以便我可以设置我的popupimage(使用jquery)出现在它旁边。请记住,因为我之前有动态文本,所以它没有固定的固定位置。

2 个答案:

答案 0 :(得分:0)

参见.offset()

    echo '$("#loginbutton").click(function(e){';
    echo 'var $target = $(this);'
    echo '$("#popup").offset({ top: $target.offset().top, left: $target.offset().left+$target.outerWidth()}).css("visibility","visible");';
    echo 'e.stopPropagation();';
    echo '});';

答案 1 :(得分:0)

为什么不做Dropbox做的事情并将按钮和弹出窗口包裹在position: relative;定位元素中?相对定位元素将随动态内容一起流动,但其中的position: absolute;元素将自动相对于包装器位置。这比通过jQuery解决它简单得多。

<强>更新

# CSS
.position_me_relative {
  position: relative;
}
.within_the_relative_wrapper {
  /* 
   This will flow inside the wrapper like a normal element.
   For example, it will obey any padding you apply to the parent element.
  */
  position: relative; 
}
.absolute_popup_relative_to_wrapper {
  /* As an example:
    This will position the popup so its lower right corner
    is touching the lower right corner of the wrapper regardless
    of where the wrapper shows up on the page.
  */ 
  position: absolute;
  bottom: 0px;
  right: 0px;
  /*
    top and left can also be used for positioning
    negative values can also be used and the absolute element
    can be positioned so it appears "outside" the wrapper element
    i think if you play around with some different values for 
    top, bottom, left and right you'll get the idea pretty quick
  */
}

# Markup
<div class="position_me_relative">
  <a class="within_the_relative_wrapper"></a>
  <div class="absolute_popup_relative_to_wrapper"></div>
</div>