【问题标题】:Create an anchor link tag that just adjusts the hash without losing the query search string创建一个锚链接标签,它只调整哈希而不丢失查询搜索字符串
【发布时间】:2015-08-02 10:05:35
【问题描述】:

假设当前网址为:http://server.com/?key=value#/foo

在一个普通的锚标签链接中,以下只会影响锚哈希:

<a href="#/bar">LINK</a>

URL 变为:http://server.com/?key=value#/bar

但是,我正在从另一个 .html 文件导入的 Web 组件的模板中添加链接。因此,为了使锚散列相对于加载的页面而不是组件的html,我需要指定链接如下:

<a href="/#/bar">LINK</a>

但是,这样的链接会导致查询搜索字符串丢失:http://server.com/#/bar

这里有干净的解决方案吗?当然,解决方法是创建一个继承自手动更新 window.document.location 的新元素。

【问题讨论】:

    标签: html hyperlink anchor web-component


    【解决方案1】:

    所以,我目前的解决方法是创建一个继承自 &lt;a&gt; 的新锚标记,它接受属性 hash 而不是 href(使用 Polymer 0.9):

    <dom-module id="a-hash"></dom-module>
    <script>
        Polymer({
            is: 'a-hash',
            extends: 'a',
            hostAttributes: { href: "" },
            properties: { hash: String },
            listeners: { tap: '_ontap', click: '_onclick' },
            _onclick: function(e) { e.preventDefault(); },
            _ontap: function(e) {
                e.preventDefault();
                document.location.hash = this.hash;
            }
       });
    </script>
    

    用法:

    Link: <a is=a-hash hash="/client/side/route">Click me</a>
    

    【讨论】:

      【解决方案2】:

      我找到了一种更简洁的解决方案,可以在新的 Web 组件中添加相对链接。只需添加一个:

      <base href="../../" />
      

      到组件的 .html 文件的顶部(假设您将自定义元素保存在 elements/element-name 子目录中),然后您可以添加普通锚点,例如:

      <a href="#/bar>LINK</a>
      

      并且它将相对于原始应用的 URL 而不是组件的 html 创建,而不会丢失查询字符串或重新加载。

      请记住,组件中的所有链接现在都将相对于应用程序的根目录而不是组件,因此可能需要相应地更新其他引用。

      【讨论】:

      • 当然,这在 Firefox 或 IE10 中似乎不起作用,因为它们似乎没有正确使用 来调整 标签...
      • 实际上,问题出在 webcomponents.js polyfill 中。我有一个待处理的推送请求来解决这个问题。但是,在硫化过程中可能会出现另一个问题,我不希望与&lt;base&gt; 标签很好地配合。
      猜你喜欢
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      相关资源
      最近更新 更多