通过引用外部页面中的锚点扩展隐藏的div

通过引用外部页面中的锚点扩展隐藏的div

本文介绍了通过引用外部页面中的锚点扩展隐藏的div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本在页面加载时隐藏(显示:无)列表中的某些div。 Div内容代表书的描述,整个列表是某种书目。每个div都有一个id,例如div1,div2等。

I have a script which hides (display:none) certain divs in the list on page load. Div contents represents description of a book, and the whole list is some sort of bibliography. Every div has an id, for example, "div1", "div2" etc.

<ul>
<li><div class="hidden" id="div1"></li>
<li><div class="hidden" id="div1"></li>
...
</ul>

还有另一个带有菜单的页面,其中包含每个这样一个div的锚定链接:

And there's another page with a menu, which consists of anchored links to every such a div:

<ul>
<li><a href="bibl.html#div1"></li>
<li><a href="bibl.html#div2"></li>
...
</ul>

我希望隐藏的div在单击其他页面上的链接时自动扩展。我尝试了一些window.location.href的东西,但无济于事 - 我的JS还很弱。我理解它应该采用当前url的逻辑并检查它是否为#,然后在id属性中搜索具有右边部分的元素。非常感谢很多人。)

I want the hidden div to autoexpand when the link on another page is clicked. I tried some window.location.href stuff, but to no avail - my JS is weak yet. As I understand the logic it should take the current url and check it for "#", then search for an element with the part to the right in the id attribute. Thanks a lot kind people.)

推荐答案

你可以在目标页面上做这样的事情:

You can do something like this on the target page:

window.onload = function() {
    var hash = window.location.hash; // would be "#div1" or something
    if(hash != "") {
        var id = hash.substr(1); // get rid of #
        document.getElementById(id).style.display = 'block';
    }
};

基本上,您检查页面加载窗口的href是否附加了散列。如果是,则找到< div> 并将样式显示更改为阻止。

Essentially, you check on the page load whether the window's href has a hash attached to it. If it does, you find the <div> and change the style display to block.

这篇关于通过引用外部页面中的锚点扩展隐藏的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 15:41