在其他元素上显示 div

时间:2021-04-15 17:07:00

标签: html jquery css

我想使用复选框作为选项实现多选。

问题是带有选项的 div 会调整同一行上其他元素的大小。

我的代码是:

<html>
    <head>  
        <style>
            .multiselect {
              width: 200px;
            }
            .selectBox {
              position: relative;
            }
            .selectBox select {
              width: 100%;
              font-weight: bold;
            }
            .overSelect {
              position: absolute;
              left: 0;
              right: 0;
              top: 0;
              bottom: 0;
            }
            #checkboxes {
              display: none;
              border: 1px #dadada solid;
            }
            #checkboxes label {
              display: block;
            }
            #checkboxes label:hover {
              background-color: #1e90ff;
            }   
        </style>    
        <script>
            var expanded = false;

            function showCheckboxes() {
              var checkboxes = document.getElementById("checkboxes");
              if (!expanded) {
                checkboxes.style.display = "block";
                expanded = true;
              } else {
                checkboxes.style.display = "none";
                expanded = false;
              }
            }       
        </script>
    </head>
    <body>
        <div style="height:60px;background:green;width:500px"></div>
        <div id="mainButtonsContainer" style="display:flex">
        
            <button>Button1</button>
            <button>Button2</button>
        
            <div class="multiselect">
                <div class="selectBox" onclick="showCheckboxes()">
                    <select>
                        <option>Select an option</option>
                    </select>
                <div class="overSelect"></div>
            </div>
            <div id="checkboxes">
                <label for="one"><input type="checkbox" id="one" />First checkbox</label>
                <label for="two"><input type="checkbox" id="two" />Second checkbox</label>
                <label for="three"><input type="checkbox" id="three" />Third checkbox</label>
            </div>
        </div>
            <button>Button3</button>
            <button>Button4</button> 
        </div>
        <div style="height:60px;background:red;width:500px"></div>
    </body>
</html>

结果是: enter image description here

预期的结果是: enter image description here

id 为 checkboxes 的元素的高度可以改变(选项可以动态添加),但它应该显示在红色背景的 div 上(以及其他如果存在)。

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您需要从具有绝对定位的普通文档流中删除 #checboxes div,并且由于您希望它跟踪 select 位置,因此您需要通过移动 {{ 1}} 在 #checkboxes 中,这样它们就可以有相同的父级。

相关问题