Linking to a section of a site that is hidden by a

2019-08-07 08:49发布

I am using a bit of JavaScript to show/hide sections of a site when a tab is clicked. I'm trying to figure out if there is a way I can link back to the page and have a certain tab open based on that link.

Here is the JS:

   var ids=new Array('section1','section2','section3','section4');

function switchid(id, el){  
    hideallids();
    showdiv(id);

    var li = el.parentNode.parentNode.childNodes[0];
    while (li) {
        if (!li.tagName || li.tagName.toLowerCase() != "li")
            li = li.nextSibling; // skip the text node
        if (li) {
          li.className = "";
          li = li.nextSibling;
        }
    }
    el.parentNode.className = "active";
}

function hideallids(){
    //loop through the array and hide each element by id
    for (var i=0;i<ids.length;i++){
        hidediv(ids[i]);
    }         
}

function hidediv(id) {
    //safe function to hide an element with a specified id
        document.getElementById(id).style.display = 'none';
}

function showdiv(id) {
    //safe function to show an element with a specified id        
        document.getElementById(id).style.display = 'block';
}

And the HTML

<ul>
<li class="active"><a onclick="switchid('section1', this);return false;">One</a></li>
<li><a onclick="switchid('section2', this);return false;">Two</a></li>
<li><a onclick="switchid('section3', this);return false;">Three</a></li>
<li><a onclick="switchid('section4', this);return false;">Four</a></li>
</ul>

<div id="section1"  style="display:block;">   
<div id="section2" style="display:none;">  
<div id="section3" style="display:none;">  
<div id="section4" style="display:none;">

I haven't been able to come up with a way to link back to a specific section. Is it even possible with this method?

Thanks!

2条回答
孤傲高冷的网名
2楼-- · 2019-08-07 09:30

HTML functionality is entirely independent of CSS. Therefore the following code will always work even if the intended section is set to display:none.

<a href="#section3">Link to section3</a>
查看更多
孤傲高冷的网名
3楼-- · 2019-08-07 09:42

You could run some script when your page loads that checks the url hash & loads the appropriate section:

// on page load
var sectionid = /section\d/i.exec(location.hash);
if (sectionid) {
    var link = document.getElementById(switchid[0] +"_link");
    switchid(sectionid[0], link);
}

& add an id to your links:

<li><a id="section2_link" onclick="switchid('section2', this);return false;">Two</a></li>
查看更多
登录 后发表回答