Html 当用户单击锚定链接时,部分内容将位于固定标题下
我正在尝试创建一个锚定链接,这样当用户单击菜单上的一个项目时,它就会转到指定的目的地。我的菜单包括三个项目(一、二、三)。例如,当我单击“三”时,它会跳到“三”,但其标题位于标题下。我怎样才能防止呢?我希望用户能够看到标题。 请注意,我希望我的标题是固定的,我希望内容滚动到标题后面 HTML:Html 当用户单击锚定链接时,部分内容将位于固定标题下,html,css,Html,Css,我正在尝试创建一个锚定链接,这样当用户单击菜单上的一个项目时,它就会转到指定的目的地。我的菜单包括三个项目(一、二、三)。例如,当我单击“三”时,它会跳到“三”,但其标题位于标题下。我怎样才能防止呢?我希望用户能够看到标题。 请注意,我希望我的标题是固定的,我希望内容滚动到标题后面 HTML: <body> <header> <nav> <ul> <li><a href="#one"
<body>
<header>
<nav>
<ul>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
</ul>
</nav>
</header>
<section>
<div id="one">
<h1>One</h1>
<p>Text...</p>
</div>
<div id="two">
<h1>Two</h1>
<p>Text...</p>
</div>
<div id="three">
<h1>Three</h1>
<p>Text...</p>
</div>
</section>
<footer>
</footer>
</body>
body {
background-color: #cf8;
}
header {
background-color: #000;
height: 4em;
width: 100%;
top: 0;
left: 0;
position: fixed;
}
nav ul {
list-style: none;
}
nav ul li {
margin-top: 0em;
padding: 5px;
float: left;
}
nav ul li a {
color: white;
text-decoration: none;
}
section {
height: auto;
width: 50%;
margin-top: 4em;
margin-left: 25%;
}
#one,#two,#three {
margin-top: 1em;
}
div {
background-color: #c00;
height: auto;
width: 100%;
}
footer {
background-color: #000;
height: 2em;
width: 100%;
clear: both;
}
,
,即使不使用JavaScript也可以实现这一点,只需在每个部分之前添加与菜单相同高度和负上边距的空div即可。 像这样:
<div id="one"></div>
<div>
<h1>One</h1>
...
请参阅:(或全屏)我建议改用基于jQuery的解决方案(p/s:See[Edit#2]了解最终代码,其中我还检测
window.location.hash
属性):
对于
-标记,将内联样式定义为style=“z-index:1;位置:绝对;”
及
对于
-标记,将内联样式定义为style=“z-index:2;位置:绝对;”
在这种情况下,部分-标记中的内容将在导航菜单上方可见。您需要使用javascript转到指定的部分,并根据固定标题的高度将滚动调整为高度。我建议不要使用此解决方案,只是因为它没有语义意义——空的HTML元素不应该用于此目的。谢谢你的回答。它适用于我提供的第一个JSFIDLE,但不适用于我发布的第二个JSFIDLE版本。
h1{ margin-top:0em; }
#one,#two,#three { margin-top:-4em; height:4em; }
$(function() {
// Only trigger .click() event when the link points to an internal anchor
$("header a[href^='#']").click(function(e) {
// Get the ID of the target
var target = $(this).attr("href");
// Animated scrolling to the vertical offset of the target element
// PLUS the outer height of the <header> element
$("html, body").animate({
scrollTop: $(target).offset().top - $("header").outerHeight()
});
// Prevent default scrolling action
// (I didn't use return false, because it stops event bubbling, too)
e.preventDefault();
});
});
$(function () {
// Scroll to function
function scrollTo(ele) {
$("html, body").animate({
scrollTop: $(ele).offset().top - $("header").outerHeight()
});
}
// Detect location hash
if (window.location.hash) {
scrollTo(window.location.hash);
}
// Detect click event
$("header a[href^='#']").click(function (e) {
var target = $(this).attr("href");
scrollTo(target);
e.preventDefault();
});
});