如果div高度超过300 addclass否则如果高度不是300则删除calss

时间:2016-05-11 11:42:42

标签: jquery css

我想在高度超过300px时添加滚动条,但如果高度不超过300则滚动将被移除。

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以通过检查其高度来检查此项以添加动态滚动条:

检查:http://jsfiddle.net/reigel/p3FFL/

$(function(){
    alert('content 1: ' + $('#my_div1').hasScrollBar());
    alert('content 2: ' + $('#my_div2').hasScrollBar());
});

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);

答案 1 :(得分:0)

您也可以通过CSS进行处理。

以下是jsfiddle的示例: http://jsfiddle.net/justjoe22/nw7noj4h/5/

HTML:

<div id="scroll1">
  <ul>
    <li>
      <div>I have some text here that is longer than 300px height, but its height is undefined (height can be between 0 and whatever)</div>
    </li>
    <li>
      <div>I have text here less than 300px height</div>
    </li>
  </ul>
</div>
<div id="scroll2">
  <ul>
    <li>
      <div>I have some text here that is longer than 300px height, but its height is undefined (height can be between 0 and whatever)</div>
    </li>
    <li>
      <div>I have text here less than 300px height</div>
    </li>
  </ul>
</div>

CSS:

#scroll1,
#scroll2 {
  max-height: 300px;
  margin-bottom: 100px;
  overflow: hidden;
}

ul {
  max-height: inherit;
  list-style-type: none;
  padding: 0px;
}

li {
  max-height: inherit;
  overflow: auto;
}

li:nth-of-type(even) {
  background-color: #ddd;
}

#scroll1 li div {
  height: auto;
}

#scroll1 li div {
  height: 400px;
}