如何在另一个div上重叠html div?

时间:2019-08-10 07:49:51

标签: javascript html css checkbox html-select

为了在html中创建多节下拉菜单,我使用普通选择和带有选项的div作为复选框。当我单击选择时,div出现在以下元素的顶部。但是我需要带有复选框的div,因为它与以下元素重叠。这是我的代码。

代码:

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;
  }
}
.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;
}
<form>
  <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 type="button">Submit</button>
    </div>
  </div>
</form>

如何更改代码以满足要求?

1 个答案:

答案 0 :(得分:2)

position: absolute;用于#checkboxes

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;
  }
}
.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;
  background: #fff;
  position: absolute;
  border: 1px #dadada solid;
  width: 100%;
}

#checkboxes label {
  display: block;
}

#checkboxes label:hover {
  background-color: #1e90ff;
}
<form>
  <div class="multiselect">
    <div class="selectBox" onclick="showCheckboxes()">
      <select>
        <option>Select an option</option>
      </select>
      <div class="overSelect"></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>
    <div>
      <button type="button">Submit</button>
    </div>
  </div>
</form>