css - 如何仅在某些条件下添加样式?
问题描述
如何仅在特定条件下添加样式?
我正在开发一个具有最大高度的 div,并且内容不断添加到其中。div 随着更多内容的添加而增长,但是当它达到最大高度时,它会停止增长并获得一个滚动条。
那时,我想为 div 添加一个边框,以给人一种内容在底部边框下方继续的印象。
这是代码的一个非常简化的版本:
<html>
<head>
<style>
.will-get-border {
/* border: 1px solid black; // <-- only if height >= 100px */
max-height: 100px;
overflow: auto;
}
</style>
<script>
function AddListItem() {
var ul = document.getElementById('unorderedList');
var li = document.createElement('li');
li.innerHTML = 'This is a list item.';
ul.appendChild(li);
}
</script>
</head>
<body>
<div class="will-get-border">
<ul id="unorderedList"></ul>
</div>
<input type="button" onclick="AddListItem()" value="Add list item" />
</body>
</html>
对于这样的事情,我需要 SASS 还是 LESS?
解决方案
你应该用 JavaScript 来处理这个!这个过程非常简单,场景就像你想添加元素时需要添加一个条件,如:
if(el.count > 5) { // also you can get the parent element and check the `max-height` property of it
// do some stuff, in your case set the max height to the parent element like
const parent = document.querySelector('.parentEl')
parent.style.maxHeight = yourMaxHeihgtValue
}
或者您可以检查元素maxheight
是否大于您的目标阈值,如下所示:
const parent = document.querySelector('.parentEl')
const targetMaxHeight = parent.style.maxHeight
if( targetMaxHeight >= thresholdValue ) {
// set the parent max height to the threshold value
parent.style.maxHeight = yourMaxHeihgtValue
}
请注意,您必须在每次添加时运行此代码,方法是将其包装到一个函数中并在您的AddListItem
函数中调用它。
推荐阅读
- vue.js - 兄弟姐妹交流
- python-3.x - Geopandas 读取 gdb 层名称以在 for 循环中进行对象
- javascript - 获取公会成员并过滤他们(Discord.js)
- flutter - 有没有更好的异步加载数据到 CupertinoPicker 的方法?
- git - Git错误“致命:无效的分支名称:init.defaultBranch =”
- regex - 正则表达式只允许星号(*)一次并最终
- angular - 以角度创建具有日期和星期的数组数组
- python - Ansible set_fact 列表字典
- powershell - 自动将 PowerBI 报告上传到工作区列表的 PowerShell 脚本
- chisel - 凿子:在最终的 Verilog 中获取信号名称