【问题标题】:Addressing instability in anchors for mobile web解决移动网络锚点的不稳定性
【发布时间】:2017-08-22 18:18:39
【问题描述】:

我在 JQ 中有一个相当密集(但非常简单)的 UI,其中需要锚点来定位 UI。

问题出在 iOS/Chrome (webkit) 和其他各种浏览器中。当一个锚点被点击大约 50% 的时间时,a 标签将触发 Chrome URL 地址栏向下滑动,再次按下它就会消失。偏移很严重,没有bueno。

正如您所料,这会扰乱 UI 定位,而且地址栏偏移很难预测,因为它是设备+屏幕尺寸的反应。

我认为这是一个错误,当第一个片段用于以前没有片段状态或片段状态更改(新的或更改的)时。这些操作或类似操作是在告诉浏览器“点击了一个标签,激活了 url bar”。

我喜欢这个解决方案(CSS),但这并不能解决问题,因为地址栏不是可靠预测的元素(除非我想为一个小问题编写愚蠢数量的 JS):

https://stackoverflow.com/a/13184714/860715

我将跳过冗长的全屏 API,因为并非所有移动设备都具有该功能。

我目前在测试中的解决方案是将onclick="return;" 添加到锚定UI 的a 标记中。这种方法似乎捕获了锚活动并跳过了触发地址栏的a标签。

关于各种移动浏览器的 UI 中更好的解决方案和/或可能存在的问题的想法。


感谢 Louys Patrice Bessette 的解决方案,需要稍作修改:

$(document).ready(function(){
    $("a").on("click", function(e){
      if( $(this).attr("href").substr(0,1) == "#" && $(this).attr("href").length > 1 ){
        var targetPos = $(document).find("a[name='"+$(this).attr("href").substr(1)+"']").offset().top;
        $("html, body").scrollTop(targetPos);
        e.preventDefault();  // this was moved -<-<
    }
});});

【问题讨论】:

    标签: javascript jquery ios google-chrome mobile


    【解决方案1】:

    我会阻止锚点在滚动页面时的默认行为。

    $(document).ready(function(){
      $("a").on("click", function(e){
    
        // It the href attribute begins with # and is not ONLY #
        if( $(this).attr("href").substr(0,1) == "#" && $(this).attr("href").length > 1 ){
    
          // Prevent the default anchor behavior.
          e.preventDefault();
    
          // Get the offset of the target a having the name attribute matching the href of the clicked anchor.
          var targetPos = $(document).find("a[name='"+$(this).attr("href").substr(1)+"']").offset().top;
    
          // Scroll the page to that position.
          $("html, body").scrollTop(targetPos);
        }
      });
    });
    

    【讨论】:

    • 非常有趣的想法。我会试试这个,但我认为 Chrome 的行为仍然会妨碍。随着地址栏的出现和消失,我将放入一些 JS 来观察屏幕垂直大小。将在部署过程中进行报告。
    • 地址栏不“来来去去”不是更好吗? ;) 上述解决方案应该做到这一点。
    • 好的,成功了,e.preventDefault(); 发错地方了,需要关注scrollTop。在 Chrome/Webkit iOS、Chrome OSX、FFox OSX 上测试。这个解决方案是我所期待的,但我的问题是保留一些行为并否认其他行为。干得好/谢谢。在原文中发布更正。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    相关资源
    最近更新 更多