【问题标题】:How do I add style only under certain conditions? [duplicate]如何仅在某些条件下添加样式? [复制]
【发布时间】:2019-11-07 21:26:06
【问题描述】:

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

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

【问题讨论】:

  • 多高?如果是元素高度,则可以使用脚本,如果是媒体,则可以使用media query
  • 如果列表项始终是固定高度并且包含的​​ div 上存在最大高度,您只需进行数学运算并找出到达该溢出点需要多少项并动态添加一个带有类似element.classList.add("mystyle");的边框的类

标签: css conditional-statements


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 2022-01-07
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    相关资源
    最近更新 更多