CSS悬停卡定位

时间:2014-11-08 21:46:19

标签: javascript jquery html css css3

我正在尝试使用css制作一张悬停卡片。我有一个关于页面位置的问题。

我已从codepen.io创建了此 DEMO 页面。因此,如果您位于演示页面的底部,那么您会看到气泡div显示出来。

我该怎么做才能在页面下方的三角形底部显示.bubbleenter image description here

.container{
  width:400px;
  height:400px;
  margin:0px auto;
  margin-top:50px;
}
.bubble 
{
position: absolute;
width: 250px;
height: 120px;
padding: 0px;
background: #000;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
  display:none;
}

.bubble:after 
{
content: '';
position: absolute;
border-style: solid;
border-width: 0 15px 15px;
border-color: #000 transparent;
display: block;
width: 0;
z-index: 1;
top: -15px;
left: 194px;
}
.hub:hover .bubble{
  display:block;
}
.wrp{
  width:300px;
  height:68px;
}

2 个答案:

答案 0 :(得分:10)

修改

  

我已经制作了一个jQuery插件来解决这个问题,重新定位工具提示以保持在窗口内,简单&响应。您可以在此处查看tipso

我将您的codepen分叉并重新设计on codepen

我想这就是你要找的东西:)

$('.hub').on({
  mouseenter: function() {
    $(this).addClass('zIndex');

    var top, left,
      toolTipWidth = 250,
      toolTipHeight = 120,
      arrowHeight = 15,
      elementHeight = $(this).height(),
      elementWidth = $(this).width(),
      documentHeight = $(window).height(),
      bounding = $(this)[0].getBoundingClientRect(),
      topHub = bounding.top;


    if (topHub < topHub + toolTipHeight && topHub + toolTipHeight + arrowHeight + elementHeight <= documentHeight) {

      $('.bubble').addClass('top');
      top = elementHeight + arrowHeight;
      left = -(elementWidth / 2);

    }

    if (topHub + toolTipHeight + arrowHeight + elementHeight >= documentHeight) {
      $('.bubble').addClass('bottom');
      top = -toolTipHeight - arrowHeight;
      left = -(elementWidth / 2);
    }


    $('.bubble').css({
      'top': top,
      'left': left
    });
  },
  mouseleave: function() {
    $('.bubble').removeClass('top bottom');
    $(this).removeClass('zIndex');
  }
});

答案 1 :(得分:4)

我通过以下方式找到了解决方案。

正在使用 DEMO ,但我无法使用window。如果有人能用窗户做,请回答我......

    $(document).ready(function () {
        $('.hub').mouseover(function () {
            var elementHeight = $(this).height();
            var offsetWidth = -250;
            var offsetHeight = 25;
            var toolTipWidth = $(".bubble").width();
            var toolTipHeight = $(".bubble").height();
            var documentWidth = $(document).width();
            var documentHeight = $(document).height();
            var top = $(this).offset().top;

            if (top + toolTipHeight > documentHeight) {                   
                top = documentHeight - toolTipHeight - offsetHeight - (2 * elementHeight);
            }
            var left = $(this).offset().left + offsetWidth;
            if (left + toolTipWidth > documentWidth) {                      
                left = documentWidth - toolTipWidth - (2 * offsetWidth);
            }                    
            $('.bubble').css({ 'top': top, 'left': left });
        });
    });