最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Show element based on hash in the url - Stack Overflow

programmeradmin0浏览0评论

I have a page (/categories.html) with about 50 p elements :

<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
...

Now, I want the page to only show

Blue_colored_items

if

/categories.html#BCI

is the requested url, and so on.

How should I get that working? I can change the entire html.

I have a page (/categories.html) with about 50 p elements :

<p id='BCI'>Blue_colored_items</p>
<p id='RCI'>Red_colored_items</p>
...

Now, I want the page to only show

Blue_colored_items

if

/categories.html#BCI

is the requested url, and so on.

How should I get that working? I can change the entire html.

Share Improve this question asked May 10, 2018 at 15:06 SiamakSiamak 3552 silver badges12 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

I just found this pure css working very well.

<style>
p {display: none}
:target {display: block}
</style>

Anyway, thanks for your answers, Rory and Andrei.

document.body.classList.add(window.location.hash.substring(1))

will add any existing hash as a class to your <body> element, allowing you control using CSS:

p {display:none;}
.BCI p#BCI {display: inline;}
.RCI p#RCI {display: inline;}
...

Or, you could simply search the <p> based on hash and display it:

// 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>

You can get the value from the window.location.hash property. Then you can hide the content you require excluding the specified element, something like this:

var hash = '#BCI'; // window.location.hash;

$('p').not(hash).hide();
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="BCI">Blue_colored_items</p>
<p id="RCI">Red_colored_items</p>

Note that p is a very generic selector I used only for this example. I'd suggest something much more specific for your production code.

发布评论

评论列表(0)

  1. 暂无评论