【问题标题】:How to design List with sublist and sublist should be displayed on hover of parent list如何设计带有子列表的列表,子列表应显示在父列表的悬停上
【发布时间】:2019-07-26 11:18:27
【问题描述】:
当指针悬停在查看行上时,应打开查看新记录和旧记录
<div>
<li>Add Rows</li>
<li>DeleteRows</li>
<li>View Rows
<ul>
<li>View New Records</li>
<li>View Old Records</li>
</ul>
</li>
</div>
【问题讨论】:
标签:
javascript
jquery
html
css
bootstrap-4
【解决方案1】:
纯 CSS
使用:hover 将.records 的显示更改为在您将鼠标悬停在“查看行”上时阻止。
.records {
display: none;
}
.view:hover .records {
display: block;
}
<div>
<li>Add Rows</li>
<li>DeleteRows</li>
<li class="view">View Rows
<ul class="records">
<li>View New Records</li>
<li>View Old Records</li>
</ul>
</li>
</div>
纯 Javascript
与往常一样,有多种方法可以做到这一点。您可以使用纯 JavaScript,如下所示。这使用.querySelectorAll() 来选择元素,.addEventListener() 在mouseover 和mouseleave 上做一些事情。显然,这比以前的方法更复杂、更难,但这为更多的定制留下了空间。
var records = document.querySelectorAll(".records");
var view = document.querySelectorAll(".view")[0];
view.addEventListener("mouseover", function() {
records.forEach(e => {
e.style.display = "block";
});
});
view.addEventListener("mouseleave", function() {
records.forEach(e => {
e.style.display = "none";
});
});
.records {
display: none;
}
<div>
<li>Add Rows</li>
<li>DeleteRows</li>
<li class="view">View Rows
<ul class="records">
<li>View New Records</li>
<li>View Old Records</li>
</ul>
</li>
</div>
jQuery
当然,还有一个 jQuery 方法。这使用.hover() 来检测您何时将鼠标悬停在文本上,然后您使用.show() 来显示li。然后你用.mouseout()检测你什么时候走出文字,.hide()隐藏文字。
$(".records").hide();
$(".view").hover(function() {
$(".records").show();
});
$(".view").mouseout(function() {
$(".records").hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<li>Add Rows</li>
<li>DeleteRows</li>
<li class="view">View Rows
<ul class="records">
<li>View New Records</li>
<li>View Old Records</li>
</ul>
</li>
</div>
【解决方案2】:
您可以首先使用 ul visibility hidden 和 li: hover ul visibility: visible to display on hover of parent list。
li:hover ul {
visibility: visible;
}
ul {
visibility: hidden;
}
<div>
<li>Add Rows</li>
<li>DeleteRows</li>
<li>View Rows
<ul>
<li>View New Records</li>
<li>View Old Records</li>
</ul>
</li>
</div>
【解决方案3】:
see js fiddle example here
ul {
background: #333;
}
ul li {
position: relative;
list-style: none;
display: inline-block;
color: white;
}
ul ul {
position: absolute;
left: 0;
right: 0;
top: 100%;
display: none;
padding-left: 0;
}
ul li:hover ul {
display: block;
}
ul ul li {
display: block;
width: 100%;
}
<div>
<ul>
<li>Add Rows</li>
<li>DeleteRows</li>
<li>View Rows
<ul>
<li>View New Records</li>
<li>View Old Records</li>
</ul>
</li>
</ul>
</div>