使“滚动到顶部”功能不显示在移动设备上

时间:2018-06-25 04:24:32

标签: jquery html css

我正在寻找一种简单的方法来使以下“滚动到顶部”功能不显示在移动设备上。有没有快速的解决方法?

主要是希望能够取消滚动至顶部的功能,因为移动设备的空间如此有限,并且有简便的功能性方法可以滚动至移动设备的顶部(例如,在iOS设备上点击屏幕顶部)。

以下是我正在使用的HTML,CSS,JQuery和Liquid:

{% comment %} 
  Reduce below value if you need the back to the top button to appear higher up on the page. 
  That value is in pixels.
{% endcomment %}
{% assign vertical_offset_for_trigger = 300 %}
{% comment %} 
  Vertical offset from bottom of browser for the position of the button.
{% endcomment %}
{% assign position_from_bottom = '15em' %}

<a href="#" title="Back to the top" class="back-to-top">
  <span>Top</span> <i class="fas fa-angle-double-up"></i>
</a>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">

<style>
.back-to-top {
  position: fixed;
  bottom: {{ position_from_bottom }};
  right: 10px;
  text-decoration: none;
  color: #999;
  background-color: #eee;
  font-size: 16px;
  padding: 0.3em;
  display: none;
  -webkit-border-top-left-radius: 3px;
  -webkit-border-bottom-left-radius: 3px;
  -moz-border-radius-topleft: 3px;
  -moz-border-radius-bottomleft: 3px;
  border-top-left-radius: 3px;
  border-bottom-left-radius: 3px;
  z-index: 60000;
}
.back-to-top i {
  vertical-align: middle;
}
.back-to-top span {
  padding-left: 0.5em;
}
.back-to-top i + span {
  padding-left: 0;
}
.back-to-top:hover {
  text-decoration: none;
  color: #555;
}
</style>

<script>
window.onload = function() {
 jQuery(function($) {
   var offset = {{ vertical_offset_for_trigger }};
   var duration = 500;
   $(window).scroll(function() {
     if ($(this).scrollTop() > offset) {
       $('.back-to-top').fadeIn(duration);
     } 
     else {
       $('.back-to-top').fadeOut(duration);
     }
   });
   $('.back-to-top').unbind('click.smoothscroll').bind('click', function(e) {
     e.preventDefault();
     $('html, body').animate( { scrollTop: 0 }, duration);
     return false;
   })
 });
}
</script>

2 个答案:

答案 0 :(得分:3)

添加此CSS代码:

@media (max-width: 600px), (max-height 700px) {
    .back-to-top {
        display: none !important; /* !important is used to override the jQuery style */
    }
}

它使用CSS Media Query添加CSS规则,该规则仅在浏览器窗口的宽度小于或等于600px或高度小于或等于700px时应用。

答案 1 :(得分:1)

您可以通过

查看当前屏幕来实现
var h = $(window).height();
var w = $(window).width();

然后,仅对特定的移动视图分辨率应用隐藏/显示条件。

if((h <= 480) && (w <= 640)){ 
  $('.back-to-top').hide(); 
} else {
  $('.back-to-top').show();
}

将此条件包装在函数foo()中,并在页面加载后调用该函数。
注意:将foo()放在所有页面都使用的通用js文件中。