【问题标题】:Show element based on hash in the url根据 url 中的哈希显示元素
【发布时间】:2018-10-20 21:50:42
【问题描述】:
我有一个包含大约 50 p 个元素的页面 (/categories.html):
<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
...
现在,我希望页面只显示
Blue_colored_items
如果
/categories.html#BCI
是请求的url,以此类推。
我应该如何让它发挥作用?我可以更改整个 html。
【问题讨论】:
标签:
javascript
jquery
html
css
hash
【解决方案1】:
我刚刚发现this pure css 工作得很好。
<style>
p {display: none}
:target {display: block}
</style>
无论如何,感谢您的回答,Rory 和 Andrei。
【解决方案2】:
document.body.classList.add(window.location.hash.substring(1))
将任何现有的哈希作为一个类添加到您的<body> 元素,允许您使用 CSS 进行控制:
p {display:none;}
.BCI p#BCI {display: inline;}
.RCI p#RCI {display: inline;}
...
或者,您可以简单地根据哈希搜索 <p> 并显示它:
// hardcoding hash for StackOverflow (only needed here, on SO):
window.location.hash = '#BCI';
let p = document.getElementById(window.location.hash.substring(1));
if (p) p.style.display = 'inline';
p { display: none; }
<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
【解决方案3】:
您可以从window.location.hash 属性中获取值。然后您可以隐藏您需要的内容,不包括指定的元素,如下所示:
var hash = '#BCI'; // window.location.hash;
$('p').not(hash).hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="BCI">Blue_colored_items</p>
<p id="RCI">Red_colored_items</p>
请注意,p 是一个非常通用的选择器,我仅用于本示例。我会为您的生产代码提出更具体的建议。