bootstrap调整页面大小而不是查找视口

时间:2017-01-10 10:09:32

标签: javascript jquery twitter-bootstrap bootstrap-modal

因此,当用户点击按钮时,我想打开一个popUp,具​​体取决于页面的宽度,我想相应地调整popUp的大小。

找到了一个美味的例子How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

 // Executes only in XS breakpoint
if( viewport.is('xs') ) {
    // ...
}

// Executes in SM, MD and LG breakpoints
if( viewport.is('>=sm') ) {
    // ...
}

// Executes in XS and SM breakpoints
if( viewport.is('<md') ) {
    // ...
}

问题是视点是未定义的触发

Uncaught ReferenceError: viewport is not defined
at <anonymous>:1:1

但我把它包含在我的头脑中

    <!--Viewport-->
<meta name="viewport" content="width=device-width, initial-scale=1">

我还将引导脚本从头部移动到正文。

有没有人知道什么是错的? TA

2 个答案:

答案 0 :(得分:1)

我认为他们意味着&#34; viewport&#34;作为你应该传递给函数的字符串。

&#13;
&#13;
$(window).on('resize', changeViewport($(window).width()));

function changeViewport(viewport) {
  if(viewport >= 1200) {
      console.log('lg');
  }
  else if(viewport < 1200 && viewport >= 768) {
    console.log('md');
  }
  else if(viewport < 768 && viewport >= 480) {
    console.log('sm');
  }
  else if(viewport < 480) {
    console.log('xs');
  }
}
  
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

然后您可以将字符串大小返回并检查if(viewport.is('md'))
等等......

答案 1 :(得分:1)

您需要在javascript中声明viewport变量。

在示例中,使用IIFE完成如下:

// Wrap IIFE around your code
(function($, viewport){
    $(document).ready(function() {

        // Executes only in XS breakpoint
        if(viewport.is('xs')) {
            // ...
        }

        // Executes in SM, MD and LG breakpoints
        if(viewport.is('>=sm')) {
            // ...
        }

        // Executes in XS and SM breakpoints
        if(viewport.is('<md')) {
            // ...
        }

        // Execute code each time window size changes
        $(window).resize(
            viewport.changed(function() {
                if(viewport.is('xs')) {
                    // ...
                }
            })
        );
    });
})(jQuery, ResponsiveBootstrapToolkit);

视口设置为ResponsiveBootstrapToolkit,因此您必须在项目中包含responsive-bootstrap-toolkit