【问题标题】:offset() returns different values in mobile browsersoffset() 在移动浏览器中返回不同的值
【发布时间】:2018-02-16 12:38:30
【问题描述】:

我正在尝试相对于其目标动态定位弹出窗口。它在桌面浏览器中运行良好。但是在移动浏览器中,位置是错误的。这主要是因为,在桌面浏览器中,即使页面滚动,元素的 offset() 也会给出相同的值。但是在移动浏览器中,当页面滚动时,offset() 会提供不同的值。要获得实际的偏移量,我们需要这样做,

offset.left -= window.pageXOffset
offset.top -= window.pageYOffset

但这并非在所有情况下都会发生。仅当页面未在移动浏览器中缩放时才会发生这种情况。 此处报告此问题 (https://github.com/jquery/jquery/issues/3187)。
而在此问题页面中,他们提到仅在缩放移动浏览器时才会出现此问题。

无论桌面/移动/ipad浏览器如何找到正确的偏移量?

我已经得出了一个获取元素实际偏移量的解决方案:

function getOffset( element ){
  var $body = $('body');
  var offset = element.offset();
    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
      var temp = $('<span>').css({
        position:'absolute',
        height:'20px',
        width:'20px',
        top:'0px',
        left:'0px'
      }).appendTo( $body );
      correctionOffset = temp.offset();
      correctionOffset.left = correctionOffset.left - parseFloat( $body.css('margin-left') ) - parseFloat( $body.css('border-left-width') ) ; 
      correctionOffset.top = correctionOffset.top - parseFloat( $body.css('margin-top') ) - parseFloat($body.css('border-top-width') ) ; 
      temp.remove();
      offset.left -= ( correctionOffset.left );
      offset.top -= ( correctionOffset.top );
  }
  return offset;
}

这是在移动浏览器中实现元素正确偏移的正确方法,即使在缩放时也是如此?

【问题讨论】:

    标签: javascript jquery html css mobile


    【解决方案1】:

    你可以试试这个它的工作:

    <li><a href="#scroll_to_gallery" class="bnrbuttons"></a></li>
    
    
     <script>
     jQuery(document).on('click', '.bnrbuttons a', function(event){
        event.preventDefault();
    
        if ( $(window).width() < 767) { //Set here window width accourding to your need
    
            jQuery('html, body').animate({
            scrollTop: jQuery( jQuery.attr(this, 'href') ).offset().top + 230
            }, 500);
            
        }
      else{
          jQuery('html, body').animate({
            scrollTop: jQuery( jQuery.attr(this, 'href') ).offset().top - 65
            }, 500);
      }
            
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 2014-09-10
      • 2010-10-24
      • 2016-03-27
      • 1970-01-01
      • 2012-03-25
      • 2015-02-13
      • 2011-04-27
      相关资源
      最近更新 更多