简体   繁体   English

在javascript和锚点中使用URL哈希

[英]using URL hashes in javascript AND anchors

We're using URL hashes in some places in our app to filter the display, eg #highlight=free will highlight our free content. 我们在应用程序的某些位置使用了URL哈希来过滤显示内容,例如#highlight=free将突出显示我们的免费内容。 We use javascript to process the hash, listen to hash changes. 我们使用javascript处理哈希,侦听哈希变化。 All works great. 一切都很好。

We're wondering however about the best way to mix it with "real" HTML anchor links. 但是,我们想知道将其与“真实” HTML锚链接混合的最佳方法。 ie links that point to a specific html id on the page, eg #chapter-5 . 即指向页面上特定html ID的链接,例如#chapter-5

Should we implement jumping to the right place using javascript and stop relying on the default browser behaviour? 我们是否应该使用javascript实现跳转到正确的位置并停止依赖默认浏览器行为? for example, link to #chapter=chapter-5&highlight=free and handle both filter and anchor in javascript? 例如,链接到#chapter=chapter-5&highlight=free并处理javascript中的过滤器和锚点? Or is there a safe/standard way to "mix" anchors and custom hashes? 还是有一种安全/标准的方法来“混合”锚和自定义哈希?

If your target environment allows it, then the "safe/standard way" would be to leave hashes with old-school hash (commonly seen as "hashbang") approach alone for regular in-page anchors and use modern HTML5 history API instead . 如果您的目标环境允许,那么“安全/标准方式”将是使用常规哈希值(通常被称为“ hashbang”)方法将哈希值留给常规页内锚定,而使用现代HTML5历史API代替

If you must support older browsers you can use some polyfill that resorts back to that hash. 如果您必须支持较旧的浏览器,则可以使用一些可以重新填充该哈希值的polyfill。

The comments to the question were probably the most helpful so far, and so we chose to implement anchor jumping and deal with everything after the # in javascript, and not rely on built-in support in browsers for it. 到目前为止,对该问题的评论可能是最有用的,因此我们选择实现锚点跳转并处理javascript中#之后的所有内容,而不是依赖于浏览器中的内置支持。

For those interested, we use a combination of jquery.deparam , URI.js and some custom code to listen to hash changes and hook into our own functions. 对于那些感兴趣的人,我们结合使用jquery.deparam ,URI.js和一些自定义代码来侦听哈希变化并连接到我们自己的函数中。 We also played with Hasher.js which looked nice, so we might use it in future. 我们还玩了看起来不错的Hasher.js ,因此将来可能会使用它。

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

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