基于窗口大小动态更改类名称 [英] Dynamically changing class name based on window size

查看:102
本文介绍了基于窗口大小动态更改类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Twitter Bootstrap使用以下布局(简化此问题)创建响应式网站:

I am using Twitter Bootstrap to create a responsive site using the following layout (simplified for this question):

<div class="container-fluid">
    <div class="row-fluid">
        <!-- Left menu -->
        <div class="span2">
            <div class="sidebar-nav">
                MENU CONTENT GOES HERE
            </div>
        </div>

        <!-- Content -->
        <div id="mainContent" class="span7">
            MAIN CONTENT GOES HERE
        </div>

        <!-- Right column -->
        <div id="rightColumn" class="span3 hidden-phone hidden-tablet">
            RIGHT COLUMN GOES HERE
        </div>
    </div>
</div>

当浏览器窗口调整为平板电脑大小时,rightColumn div按预期隐藏 -

When the browser window resizes to tablet size, the rightColumn div is hidden as expected - but it leaves white space next to the mainContent div (with a size of span3).

我想让mainContent div扩展到全宽(因此它填充的span10大小匹配) 。

I would like the mainContent div to expand to full width (so it fills out matches span10 in size).

我使用下面的jQuery代码来动态改变mainContent div的类名,以使它成为这个(它按预期工作):

I am using the following jQuery code to dynamically change the class name for the mainContent div to achive this (and it works as expected):

$(document).ready(function() {
    var $window = $(window);

        // Function to handle changes to style classes based on window width
        function checkWidth() {
        if ($window.width() < 980) {
            $('#mainContent').removeClass('span7').addClass('span10');
            };

        if ($window.width() >= 980) {
            $('#mainContent').removeClass('span10').addClass('span7');
        }
    }

    // Execute on load
    checkWidth();

    // Bind event listener
        $(window).resize(checkWidth);
});

我的问题:这是在浏览器窗口调整大小时处理Twitter Bootstrap中跨度更改的首选方式?或者我应该更改span7的平板电脑屏幕尺寸的CSS以匹配span10?

My question: is this the preferred way to handle changes to spans in Twitter Bootstrap when the browser window resizes? Or should I just change the CSS for span7 for tablet screen sizes to match that of span10?

推荐答案

我删除了Javascript代码,并将其替换为Bootstrap CSS的简单更改,将span7的宽度更改为与平板电脑屏幕尺寸的span10相同的宽度:

I will answer it myself: I removed the Javascript code and replaced it with this simple change to the Bootstrap CSS to change the width of span7 to the same width as span10 for tablet screen sizes:

@media (max-width: 979px) and (min-width: 768px) {
    .row-fluid .span7 {
    width: 82.87292817100001%;
    }
}

这篇关于基于窗口大小动态更改类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆