有没有办法只在小尺寸(移动)设备上运行JavaScript?

时间:2014-01-29 13:14:18

标签: ruby-on-rails zurb-foundation

我正在尝试使用Foundation和Rails在手机上运行javascript(和haml,这是haml示例,但不要注意这一点)。

我正在做这样的事情:

.row
 =# something for large screens
    .row.show-for-small-only
      .small-10.small-centered.columns
        = javascript_tag "$('.someClassIPointTo').myfunction();"

所以我试图只为小尺寸屏幕运行这个javascript,而不是大屏幕。有没有办法做其他的然后复制代码?

2 个答案:

答案 0 :(得分:0)

您可以使用简单的javascript来检测设备是否可移动,然后运行您想要的代码。

if( (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) &&
    (window.innerWidth < SCREEN_WIDTH) && (window.innerHeight < SCREEN_HEIGHT) ) {
 // some code..
}

来源:What is the best way to detect a mobile device in jQuery?

答案 1 :(得分:0)

我已经找到了我自己的问题的答案,在这里:

我添加了一个班级.my_indicator_class inside .show-for-small。像这样的东西(例子):

.show_for_small
 .my_indicator_class

然后在我的javascript代码中,我用它来检查这个元素是否可见,如下所示:

var isVisible = $('.my_indicator_class').is(":visible");

if(isVisible){
  //My code that will run only for small screens
}else{
  // Code for big screens :)
}

而且,那就是它。