css 下拉菜单位置在窗口视图之外

qnzebej0  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(133)

我有一个Press Me按钮,当按下时会打开一个菜单。我的JavaScript工作,但我有以下CSS和HTML问题:
当你点击Press Me的时候,菜单会打开,但是它部分不在可见的窗口中。你必须向右滚动才能看到问题。
我尝试使用right: px与一些数字,但现在它根本没有响应。

// NO PROBLEM HERE IN JAVASCRIPT!
function myFunction() {
    document.getElementsByClassName('dropdown-content')[0].classList.toggle('show');
}
window.onclick = function(event) {
    if (!event.target.matches('#verify-name')) {
        var dropdowns = document.getElementsByClassName('dropdown-content');
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
            }
        }
    }
}
.buttons {
    display: flex;
    justify-content: flex-end;
    color: red;
}
.dropdown-content {
    display: none;
    position: absolute;
    width: 120px;
        padding: 14px;
        background-color: yellow;
}
.show {
    display: flex;
}
<div class="buttons">
    <div>
        <a id="verify-name" onclick="myFunction()">Press Me</a>

        <div class="dropdown-content">
            <span>Logout</span>
        </div>
    </div>
</div>
uajslkp6

uajslkp61#

我只是从.dropdown-content类中删除position: absolute,并将text-align: right;添加到.buttons类中。

// NO PROBLEM HERE IN JAVASCRIPT!
function myFunction() {
  document.getElementsByClassName('dropdown-content')[0].classList.toggle('show');
}
window.onclick = function(event) {
  if (!event.target.matches('#verify-name')) {
    var dropdowns = document.getElementsByClassName('dropdown-content');
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}
.buttons {
  display: flex;
  justify-content: flex-end;
  color: red;
  text-align: right;
}

.dropdown-content {
  display: none;
  direction: rtl;
  width: 120px;
  padding: 14px;
  background-color: yellow;
}

.show {
  display: flex;
}
<div class="buttons">
  <div>
    <a id="verify-name" onclick="myFunction()">Press Me</a>

    <div class="dropdown-content">
      <span>Logout</span>
    </div>
  </div>
</div>

相关问题