简体   繁体   English

使用jquery.scrollTo时,使用jQuery处理元素ID中的冒号

[英]Handling colon in element ID with jQuery when using jquery.scrollTo

I am using the jquery.scrollTo plugin on my site as follows: 我在我的网站上使用jquery.scrollTo插件,如下所示:

$('a[href^="#"]').click(function (e) {
    e.preventDefault();
    $(window).stop(true).scrollTo(this.hash, 
       { duration: 500, interrupt: true, margin: true });
});

This works 100% fine for most anchors. 这适用于大多数锚点100%罚款。 However, when scrolling to elements that contain a colon in the name, it causes jQuery to throw an exception. 但是,当滚动到名称中包含冒号的元素时,会导致jQuery抛出异常。 So, for example, the following HTML does not scroll as it should: 因此,例如,以下HTML不会按原样滚动:

<a rel="footnote" href="#fn:1">1</a>
...
<ol>
    <li id="fn:1">
        Footnote 
        <a class="footnote-return" href="#fnref:1">
            <sup>[return]</sup>
        </a>
    </li>
    ...
</ol>

This is especially a problem when rendering markdown footnotes. 在渲染markdown脚注时,这尤其是个问题。 The markdown processor that I use ( Black Friday ), as I assume most other processors, render footnotes with a convention that contains a colon in every cross-reference. 我使用的降价处理器( 黑色星期五 ),我假设大多数其他处理器,使用在每个交叉引用中包含冒号的约定来呈现脚注。

Can anyone help? 有人可以帮忙吗?

All you need to do is escape the colons ( .replace(':', '\\\\:') ): 你需要做的就是逃避冒号( .replace(':', '\\\\:') ):

$('a[href^="#"]').click(function (e) {
  e.preventDefault();
  $(window).stop(true).scrollTo(this.hash.replace(':', '\\:'), 
    { duration: 500, interrupt: true, margin: true });
});

Working example: 工作范例:

 $('a[href^="#"]').click(function (e) { e.preventDefault(); $(window).stop(true).scrollTo(this.hash.replace(':', '\\\\:'), { duration: 500, interrupt: true, margin: true }); }); 
 ol { margin: 90vh 0; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-scrollTo/2.1.2/jquery.scrollTo.min.js"></script> <a rel="footnote" href="#fn:1">1</a> ... <ol> <li id="fn:1"> Footnote <a class="footnote-return" href="#fnref:1"> <sup>[return]</sup> </a> </li> ... </ol> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM