首页 > 新浪微博 鼠标悬停到用户头像时弹出的card是怎么实现的

新浪微博 鼠标悬停到用户头像时弹出的card是怎么实现的


没错就是这个神奇的东西。。。还会根据布局自动选择浮在上方还是下方。。。


其实前端太好实现了,关键在于后台读取数据,用户数亿级别,如何快速获取用户相关信息才是关键。


如果一个页面中有多个头像,是不是每个头像都要做一个信息框啊?就像qq空间那样。还有就是信息框中的内容应该如何动态获取呢?


inspect element

position: absolute
z-index: 9999
display: none|visible
top: xxx
left: xxx

基本思路:
1. 首先解决显示与否问题,涉及到js的hover事件,css的定位知识。当然也可以用:hover伪类实现,但是这样不能做判断。
2. 然后解决如何显示问题,根据头像距离屏幕区域四边的距离,按照上 > 下,右 > 左 的权重顺序显示。


以前研究过这个问题,最后也实现了这个效果,贴下部分代码(很早以前写的,当时还没养成好的习惯,所以代码质量很差,题主主要参考思路即可):

  Tooltip.prototype.show = function() {

    elTopLocation = this.getBoundingClientRect().top;
    elBottomLocation = window.innerHeight - this.getBoundingClientRect().bottom;
    elLeftLocation = this.getBoundingClientRect().left;
    elRightLocation = window.innerWidth - this.getBoundingClientRect().right;

    if(elLeftLocation < minVerticalDistance) {
      $(this).addClass('hint hint--right');
      this.direction = 'right';
    } else {
      if(elRightLocation < minVerticalDistance) {
        $(this).addClass('hint hint--left');
        this.direction = 'left';
      } else {
        if(elBottomLocation < minHorizonDistance) {
          $(this).addClass('hint hint--top');
          this.direction = 'top';
        } else {
          $(this).addClass('hint hint--bottom');
          this.direction = 'bottom';
        }
      }
    }
  };

大致讲下思路,先实现上下左右四种浮动效果,然后计算出元素相对于浏览器窗口的相对位置进行判断,继而选择特定的效果。
接受 @公子 批评,修改代码如下:

Tooltip.prototype.show = function() {

    elTopLocation = this.getBoundingClientRect().top;
    elBottomLocation = window.innerHeight - this.getBoundingClientRect().bottom;
    elLeftLocation = this.getBoundingClientRect().left;
    elRightLocation = window.innerWidth - this.getBoundingClientRect().right;

    var direction;
    direction = elLeftLocation < minVerticalDistance ? 'right' : 'left';
    direction = elBottomLocation < minHorizonDistance ? 'top' : 'bottom';

    $(this).addClass('hint hint--'+direction);
    return this.direction = direction;
};

下次再也不敢贴奇葩代码了。

【热门文章】
【热门文章】