【问题标题】:bootstrap resizing the page not finding viewport引导调整页面大小未找到视口
【发布时间】:2017-05-24 18:57:48
【问题描述】:

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

找到了一个美味的小例子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

【问题讨论】:

  • 如果它是唯一的要求" 我想打开一个弹出窗口,取决于页面的宽度我想相应地调整弹出窗口的大小。" 不是解决方案吗以%vw 为单位定义弹出窗口的CSS 样式宽度?

标签: javascript jquery twitter-bootstrap bootstrap-modal


【解决方案1】:

我认为他们的意思是“视口”作为你应该传递给函数的字符串。

$(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');
  }
}
  
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

那么您可以将大小作为字符串返回并检查if(viewport.is('md'))
等等……

【讨论】:

  • 感谢您的帮助。将引用的文件移动到页面顶部而不是正文标记内解决了我的问题(即使示例说将它们放在正文标记内....anywho)您的回答确实有帮助...谢谢
【解决方案2】:

您需要在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

【讨论】:

  • 感谢您的帮助。将引用的文件移动到页面顶部而不是正文标记内解决了我的问题(即使示例说将它们放在正文标记内......任何人)你的回答确实有帮助......谢谢
猜你喜欢
  • 1970-01-01
  • 2021-04-23
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多