try 以下操作:
<!DOCTYPE html>
<html lang="es">
<head>
<script type="text/javascript">
function getSelectHeight(rowsCount) {
var rowsHtml = '';
for (var i = 0; i < rowsCount; i++)
rowsHtml += '<option>.</option>';
var div = document.createElement('div');
div.innerHTML = '<select size="' + rowsCount + '" style="width: 250px;visibility:hidden">' + rowsHtml + '</select>';
document.body.after(div);
var height = div.offsetHeight;
div.remove();
return height;
}
function setSelectorHeight() {
var select = document.getElementById('selector');
var rowsCount = select.getAttribute('size');
select.style.height = getSelectHeight(rowsCount) + 'px';
}
function addOpt() {
let selector = document.getElementById("selector");
let opt = document.createElement("option");
opt.innerHTML = "New option";
selector.appendChild(opt);
}
</script>
</head>
<body onload="setSelectorHeight()">
<select size="8" style="width: 250px" id="selector"></select>
<button type="button" onclick="addOpt()">Click me</button>
</body>
</html>
getSelectHeight
给出指定rowsCount
的 Select 器的实际高度.在这里,我们添加了一个包含rowsCount
个项目的不可见 Select 器,获取它的实际高度并删除该 Select 器.
在body onload
上运行setSelectorHeight
:找到 Select 器,判断行数(size
属性)并设置 Select 器的高度.我使用这种风格是因为设置offsetHeight
不起作用.