gpt4 book ai didi

javascript - 一个 html 文件中的多个页面,每一页上没有固定的导航

转载 作者:行者123 更新时间:2023-12-02 21:16:16 26 4
gpt4 key购买 nike

主页只有几个按钮,用于显示用户指定的内容。

#home 中的按钮不在标题中,因此按钮将仅显示在 #home 上。

<section id="home">
<a href="#content">content</a>
<a href="#something">something</a>
<a href="#someelse">someelse</a>
</section>
<section id="content">
<section id="something">
<section id="someelse">

我在css上找到了:target方法,它看起来很容易使用并且工作正常,但是#home没有显示。似乎只有当我在 section

之外有固定标题时它才有效
section {
display: none;
}
section:target {
display: block;
}

#home之外的每个部分都会有后退按钮,该按钮也会将用户发送到#home。这在 :target 方法上相当简单,因为我只使用了 a href="#",并且它有效。

我还能使用什么其他方法?

最佳答案

我想不出任何纯CSS方法来做到这一点,但可以很容易地用一点JavaScript来检查哈希是否为空,然后显示#home并隐藏它当有一个值时。

window.onhashchange = checkHash;

checkHash();

function checkHash() {
var home = document.getElementById('home');

//Check if the hash is empty
if (window.location.hash.substring(1) == '') {
home.style.display = 'block';
} else {
home.style.display = 'none';
}
}
.section {
display: none;
}

.section:target {
display: block !important;
}
<div id="home" class="section">
<a href="#content">Content</a>
<a href="#somthingElse">Somthing Else</a>
<h3>Home</h3>
</div>
<div id="content" class="section">
<a href="#home">Home</a>
<h3>Content</h3>
</div>
<div id="somthingElse" class="section">
<a href="#home">Home</a>
<h3>Somthing Else</h3>
</div>

淡入淡出

我使用了position:absolute,这样它们就会堆叠在一起。 z-index: -1 将使所有其余部分保持清晰,以防止指针事件重叠。 opacity: 0 显然用于淡入淡出。

我更改了 JS 脚本以简化我的 CSS。现在,当您访问 example.com/html.html 时,您会被重定向到 example.com/html.html#home (后退按钮的历史记录不会更改)。

window.onhashchange = checkHash;

checkHash();

function checkHash() {
//Check if the hash is empty
if (window.location.hash.substring(1) == '') {
history.replaceState(undefined, undefined, "#home")
}
}
.section {
position: absolute;
z-index: -1;

opacity: 0;

transition: opacity 0.5s;
}

.section:target {
z-index: 1;

opacity: 1;
}
<div id="home" class="section">
<a href="#content">Content</a>
<a href="#somthingElse">Somthing Else</a>
<h3>Home</h3>
</div>
<div id="content" class="section">
<a href="#home">Home</a>
<h3>Content</h3>
</div>
<div id="somthingElse" class="section">
<a href="#home">Home</a>
<h3>Somthing Else</h3>
</div>

关于javascript - 一个 html 文件中的多个页面,每一页上没有固定的导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60962191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com