首页 > 解决方案 > 如何仅在某些条件下添加样式?

问题描述

如何仅在特定条件下添加样式?

我正在开发一个具有最大高度的 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?

标签: cssconditional-statements

解决方案


你应该用 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函数中调用它。


推荐阅读