html设置列表显示数量并滚动例子
时间: 2023-05-30 20:05:31 浏览: 40
以下是一些示例代码,演示如何在HTML中设置列表显示数量并滚动:
1. 使用CSS的overflow属性来设置列表滚动,并设置max-height属性来限制列表显示的最大高度。
```
<style>
.scrollable-list {
overflow: auto;
max-height: 200px;
}
</style>
<div class="scrollable-list">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
<li>Item 15</li>
</ul>
</div>
```
2. 使用JavaScript来动态设置列表的高度,并在需要时启用滚动。
```
<style>
.scrollable-list {
overflow: auto;
}
</style>
<div class="scrollable-list">
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
<li>Item 7</li>
<li>Item 8</li>
<li>Item 9</li>
<li>Item 10</li>
<li>Item 11</li>
<li>Item 12</li>
<li>Item 13</li>
<li>Item 14</li>
<li>Item 15</li>
</ul>
</div>
<script>
var list = document.getElementById("list");
var maxHeight = 200;
// Set the list height to show a maximum of 5 items at a time
list.style.height = (list.children[0].offsetHeight * 5) + "px";
// Enable scrolling when the list height exceeds the maximum height
if (list.offsetHeight > maxHeight) {
list.style.height = maxHeight + "px";
list.style.overflow = "auto";
}
</script>
```