Bootstrap 4 - 如何在调整大小

时间:2018-03-13 07:26:52

标签: jquery twitter-bootstrap-4

我使用Bootstrap 4,所以我在页面上添加了以下HTML代码

HTML

<div id="device-size-detector">
    <div id="xs" class="d-block d-sm-none"></div>
    <div id="sm" class="d-none d-sm-block d-md-none"></div>
    <div id="md" class="d-none d-md-block d-lg-none"></div>
    <div id="lg" class="d-none d-lg-block d-xl-none"></div>
    <div id="xl" class="d-none d-xl-block"></div>
</div>

JS

$(document).ready(function() {

"use strict"

function getBootstrapDeviceSize() {
    return $('#device-size-detector').find('div:visible').first().attr('id');
}

function checkMenu(){
    var screen = getBootstrapDeviceSize();

    $(window).on('resize', function() {
        screen = getBootstrapDeviceSize();
    });

    if(screen == "lg" ||  screen == "xl") {
        console.log(1); 
    } else {
        console.log(0);
    }       
}

checkMenu();

});

但是我的脚本只检测屏幕大小的第一个值,并且在调整大小时没有检测到宽度的任何变化。我想我没有正确使用$(window).on('resize', function() {...},但我不明白如何修复它并让它工作?

1 个答案:

答案 0 :(得分:3)

window.resize代码移到checkMenu函数之外,并调用以下函数。

$(window).on('resize', checkMenu);

&#13;
&#13;
$(document).ready(function() {

"use strict"

function getBootstrapDeviceSize() {
    return $('#device-size-detector').find('div:visible').first().attr('id');
}

function checkMenu(){
    var screen = getBootstrapDeviceSize();    

    if(screen == "lg" ||  screen == "xl") {
        console.log(1); 
    } else {
        console.log(0);
    }       
}
checkMenu();
$(window).on('resize', checkMenu);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="device-size-detector">
    <div id="xs" class="d-block d-sm-none"></div>
    <div id="sm" class="d-none d-sm-block d-md-none"></div>
    <div id="md" class="d-none d-md-block d-lg-none"></div>
    <div id="lg" class="d-none d-lg-block d-xl-none"></div>
    <div id="xl" class="d-none d-xl-block"></div>
</div>
&#13;
&#13;
&#13;