zoukankan      html  css  js  c++  java
  • ng6.1 新特性:滚回到之前的位置

    在之前的版本中滚动条位置是一个大问题,主要表现在

    1. 使用快捷键或者手势前进/后退的时候,滚动条的位置经常是错乱的,所以只能每个页面都要重置一个滚动条的位置;

    2. #anchor1 锚点位置无法定位

    2017年10月开始解决这个问题,历时7个月终于在 6.1 beta1 中解决了。

    解决方案就是增加了一个全新的特性 Scroll Position Restoration,滚回到之前的位置。

    有人详细介绍了这个特性,点我查看

    今天我尝试了一下 ViewportScroller 的 scrollToAnchor,跳转到锚点。

    //注入 ViewportScroller
    constructor(private scroller: ViewportScroller) { }
      async ngOnInit() {
        //初始化数据之后,滚到 id='foot' 的元素那里
        this.scroller.scrollToAnchor('foot');
      }

    在页面底部添加一个 id='foot' 的元素,注意要保证该元素超过浏览器的视野,不然就不会出现滚动条了,也就看不到效果了。

    测试结果很成功,于是改成正式代码

     ngOnInit() {
       //初始化
        this.scroller.scrollToAnchor(this.route.snapshot.fragment);
     }

    结果报错了

    Uncaught (in promise): SyntaxError: Failed to execute 'querySelector' on 'Document': '#8e2c2c4e-3722-4645-bd12-af14da8cef96' is not a valid selector.
    Error: Failed to execute 'querySelector' on 'Document': '#8e2c2c4e-3722-4645-bd12-af14da8cef96' is not a valid selector.

    原来是 selector 选择器不正确,但是为什么不正确呢?看看它的实现就知道了。

    // https://github.com/angular/angular/pull/20030/files
    + scrollToAnchor(anchor: string): void { + if (this.supportScrollRestoration()) { + const elSelectedById = this.document.querySelector(`#${anchor}`); + if (elSelectedById) { + this.scrollToElement(elSelectedById); + return; + } + const elSelectedByName = this.document.querySelector(`[name='${anchor}']`); + if (elSelectedByName) { + this.scrollToElement(elSelectedByName); + return; + } + } + }

    原来内部调用的是 querySelector,在 MDN 上看一下文档,原来必须是 css 选择器

    Note: Characters that are not part of standard CSS syntax must be escaped using a backslash character. Since JavaScript also uses backslash escaping, be especially careful when writing string literals using these characters. See Escaping special characters for more information.

    而我的代码里用的是 GUID,由于以数字开头,所以不符合语法规范。解决办法就很简单了,在它前面加一个字母就行了。

     ngOnInit() {
       //初始化
        this.scroller.scrollToAnchor('a'+this.route.snapshot.fragment);
     }

    别忘了在 HTML 模版中的锚点中也要加上这个字母。

  • 相关阅读:
    LOJ 3055 「HNOI2019」JOJO—— kmp自动机+主席树
    LOJ 2586 「APIO2018」选圆圈——KD树
    bzoj 3600 没有人的算术——二叉查找树动态标号
    bzoj 1257 余数之和 —— 数论分块
    bzoj 3998 弦论 —— 后缀自动机
    bzoj 2946 公共串 —— 后缀自动机
    bzoj 4032 [ HEOI 2015 ] 最短不公共子串 —— 后缀自动机+序列自动机
    bzoj 2555 SubString —— 后缀自动机+LCT
    洛谷 P3804 [模板] 后缀自动机
    洛谷 P4106 / bzoj 3614 [ HEOI 2014 ] 逻辑翻译 —— 思路+递归
  • 原文地址:https://www.cnblogs.com/kexxxfeng/p/9297981.html
Copyright © 2011-2022 走看看