在单击右侧的元素下显示div

时间:2017-02-24 16:04:20

标签: jquery css

我关注this我为每个按钮设置了不同的弹出窗口,但我希望它们在点击按钮的右侧对齐。

enter image description here

更改

  

left:btn.offset()。left

无法让我到任何地方。



$(document).ready(function() {
  $("#button1, #button2").click(function() {
    var btn = $(this);
    var clickedId = $(this).attr("id");
    var clickedPopup = "_popup";
    $("#" + clickedId + clickedPopup).css({
      position: 'absolute',
      top: btn.offset().top + btn.outerHeight() + 10,
      left: btn.offset().left
    }).slideToggle('');
  });
});

.button_div,
.text_div {
  position: relative;
  float: right;
  margin: 0 10px;
}

#button1_popup,
#button2_popup {
  display: none;
  border: 1px solid black;
  width: 220px;
  height: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="text_div">div with unknown width</div>
<div id="button1" class="button_div"><button id="one">One</button></div>
<div id="button2" class="button_div"><button id="two">Two</button></div>
<div id="button1_popup">Message with some text</div>
<div id="button2_popup">Message with some text</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

当css完美运行时,无需在javascript中执行此操作。我建议将隐藏的div嵌套在position内,absoluteright:0$(document).ready(function() { $("#button1, #button2").click(function() { var btn = $(this); var clickedId = $(this).attr("id"); var clickedPopup = "_popup"; $("#" + clickedId + clickedPopup).slideToggle(''); }); });嵌套在一起,如下所示:

.button_div,
.text_div {
  position: relative;
  float: right;
  margin: 0 10px;
}

#button1_popup,
#button2_popup {
  display: none;
  border: 1px solid black;
  width: 220px;
  height: 100px;
  position:absolute;
  right:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="text_div">div with unknown width</div>
<div id="button1" class="button_div">
  <button id="one">One</button>
  <div id="button1_popup">Message with some text</div>
</div>
<div id="button2" class="button_div">
  <button id="two">Two</button>
  <div id="button2_popup">Message with some text</div>
</div>
for xml path('')