简体   繁体   English

JavaScript使用标签更改显示

[英]JavaScript changing display using hashtag

I'm very new to JS and have a problem with something that looks very simple. 我是JS的新手,并且看起来非常简单。 I am trying to make a code so that if the page loads with a # at the end of the url, eg. 我正在尝试创建一个代码,以便如果页面在URL的末尾加载#,例如。 www.example.com#hashtag, then a div will display, if it doesn't have a # the div wont display. www.example.com #hashtag,然后div将显示,如果它没有#div不显示。

My Code: 我的代码:

JS: JS:

<script type="text/javascript">
if(window.location.hash) {
document.getElementById("displaydiv").style.display = "block"; 
}
</script>

HTML: HTML:

<div id="displaydiv" style="display: none; height: 100px; width: 100px; 
background-color: red;"></div>

The code is correct, but the <script> is executing too early, before the <div> is rendered, so I suspect you are getting a JavaScript error in the browser. 代码是正确的,但<script> 呈现<div> 之前执行得太早,所以我怀疑你在浏览器中遇到JavaScript错误。 Did you check the browser console? 你检查过浏览器控制台了吗?

Moving the <script> after the <div> will fix it but it might be wise to put the code into a function and call it after the page has loaded, for example: <div> <script> 之后移动<script>将修复它,但将代码放入函数并在页面加载后调用它可能是明智的,例如:

<script type="text/javascript">
    function init() {
        if (window.location.hash) {
            document.getElementById("displaydiv").style.display = "block"; 
        }
    }

    window.onload = init;
</script>

see Alternative to <body onload="init ();"> 请参阅<body onload =“init();”>的替代方案

This will get the Hash (#displayDiv) and show that particular div... 这将得到哈希(#displayDiv)并显示特定的div ...

<script type="text/javascript">
  var hasher = window.location.hash;

  if(hasher.indexOf('displaydiv') > -1) {
    document.getElementById("displaydiv").style.display = "block"; 
  } else if (hasher.indexOf('anotherDiv') > -1) {
    document.getElementById("anotherDiv").style.display = "block";
  }
</script>

<div id="displaydiv" style="display: none; height: 100px; width: 100px; background-color: red;"></div>

How about a simple CSS solution using the :target selector: 如何使用:target选择器的简单CSS解决方案:

*:target {
  display: block;
}

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

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