CSS:如何更改工具提示位置以与触发元素对齐(其余代码有效)

CSS: How to change tooltip position to align to triggering element (rest of code working)

我正在尝试构建工具提示(不使用插件)并将其放置在触发元素的右侧(这里是一个输入字段),垂直对齐。

到目前为止,我有以下内容(请参阅 Fiddle 演示)。 这为我提供了我想要的具有正确布局和内容的工具提示,并通过在输入字段中单击来正确显示它,但是我找不到从输入字段正确定位它的方法(而不是在屏幕中间)。

$(document).ready(function() {
  $('.tooltipClose').on('click', function() {
    $(this).closest('div.tooltip').removeClass('tooltipShow');
  });

  $('.triggerTooltip').on('click', function() {
    $(this).next('div.tooltip').addClass('tooltipShow');
  });
});
.tooltip {
  -moz-transition: opacity 400ms ease-in;
  -webkit-transition: opacity 400ms ease-in;
  bottom: 0;
  font-family: Helvetica, Arial, Verdana, sans-serif;
  left: 0;
  right: 0;
  filter: alpha(opacity=0);
  opacity: 0;
  pointer-events: none;
  position: fixed;
  top: 0;
  transition: opacity 400ms ease-in;
  z-index: 99999;
}
.tooltipClose {
  background: #028dca;
  border-radius: 12px;
  box-shadow: 2px 2px 3px #666;
  color: #fff;
  font-weight: bold;
  line-height: 25px;
  position: absolute;
  right: -12px;
  text-align: center;
  text-decoration: none;
  top: -12px;
  vertical-align: middle;
  width: 24px;
}
.tooltipClose:hover {
  background: #00507e;
}
.tooltipFooter,
.tooltipHeader {
  border-bottom: 2px solid #ccc;
  font-size: 20px;
  font-weight: bold;
  margin: 0;
  padding: 8px 0;
  vertical-align: middle;
}
.tooltipShow {
  filter: alpha(opacity=100);
  opacity: 1;
  pointer-events: auto;
}
.tooltip > div {
  background: #fff;
  border: 3px solid #028dca;
  border-radius: 10px;
  margin: 10% auto;
  padding: 8px 16px;
  position: relative;
  width: 200px;
}
.tooltip > div:after {
  border-bottom: 12px solid transparent;
  border-right: 12px solid #028dca;
  border-top: 12px solid transparent;
  content: '';
  height: 0;
  left: 0;
  margin: -12px;
  position: absolute;
  right: 50%;
  top: 50%;
  width: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- to see tooltip in the demo -->
<div style="height: 200px;"></div>
<input type="text" class="triggerTooltip" />
<div class="tooltip">
  <div>
    <a href='javascript:void(0);' class='tooltipClose'>X</a>
    <p class='tooltipHeader'>Tooltip header</p>
    <p class='tooltipBody'>Tooltip content</p>
  </div>
</div>

演示:
Fiddle

您几乎完成了所有工作。 这里有您的 Fiddle

的更新版本

小修改来了

$('.triggerTooltip').on('click', function(){

    // First set the vertical position, use the half of the tooltip height
    $('div.tooltip').css('top', $('div.tooltip div').height()/2);

    // And for the horizontal position we just substract the field's width
    $('div.tooltip').css('left', $(this).offset().left-$(this).width());


    $('div.tooltip').addClass('tooltipShow');

});

希望对您有所帮助