jquery - How to apply a CSS property using JavaScript? - Stack Overflow

I have the following structure of the code. If the height of UL exceeds 270 pixels, then I want to add

I have the following structure of the code. If the height of UL exceeds 270 pixels, then I want to add the CSS property overflow-y:scroll; or else as it is.

<ul class="tabs">
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
</ul>

I have the following structure of the code. If the height of UL exceeds 270 pixels, then I want to add the CSS property overflow-y:scroll; or else as it is.

<ul class="tabs">
    <li>Content</li>
    <li>Content</li>
    <li>Content</li>
</ul>
Share Improve this question edited Feb 12, 2015 at 17:05 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Nov 18, 2009 at 13:14 SwatiSwati 511 silver badge2 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

The following code uses jQuery to get the height and pare it. Note that it probably needs to be visible at the point where you call this to have a valid height.

$(function() {
    $(".tabs").each( function() {
        var $this = $(this);
        if ($this.height() > 270) {
            $this.css( 'overflow-y', 'scroll' );
        }
    });
});

Note this will work on all elements with the class tabs, not just the first one.

if($(".tabs").height() > 270) {
    $(".tabs").css("overflow-y", "scroll");
}

Assuming you're using jQuery.

You can do this:

$(".tabs").attr("style", "overflow-y:scroll");

This will remove the current style from the element(s). You can also use the .css function referenced here. This will keep other style values.

$(".tabs").css("overflow-y","scroll");

You have to check if the height is over 270px. To do so use the .height() method referenced here. You need to figure out where and when you want to do this test.

Other answers give good methods to check the size. Just to add a tidbit, I prefer to keep my markup in a .css file, link that in and then apply the markup in my JavaScript file:

.scrollList
{
    overflow-y:scroll;
}

And then in the script:

$('.tabs').addClass('scrollList');

And if you want to remove it again:

$('.tabs').removeClass('scrollList');

And, if you wish to fix the size you can do that in that markup section in the .css file as well.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742360426a4429285.html

相关推荐

  • jquery - How to apply a CSS property using JavaScript? - Stack Overflow

    I have the following structure of the code. If the height of UL exceeds 270 pixels, then I want to add

    1天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信