我是初学者,我有一个我认为是一个简单的问题,我不知道如何解决。基本上我正在建立一个响应式网站,我现在的问题是除了我的index.html之外我无法使我的导航栏正确响应网站的其他部分(工作正常)。
我使用了w3schools的代码来创建我的导航栏。
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_topnav
正如我所说,它适用于我的索引文件。但是,当我在我的“新闻页面”时,它无法正常工作。它重新启动,但它在左边的导航栏上显示Home。我该怎么做才能在新闻页面上说新闻,从新闻而不是主页开始? (还有联系方式,关于我们)非常感谢!对不起,如果这是一个愚蠢的问题。这是我第一次尝试建立一个响应式网站!
这里是代码(来自w3学校的链接):
<!DOCTYPE html>
<html>
<head>
<style>
body {margin:0;}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.active {
background-color: #4CAF50;
color: white;
}
.topnav .icon {
display: none;
}
@media screen and (max-width: 600px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
</style>
</head>
<body>
<div class="topnav" id="myTopnav">
<a href="#home" class="active">Home</a>
<a href="#news">News</a>
<a href="#contact">Contact</a>
<a href="#about">About</a>
<a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">☰</a>
</div>
<div style="padding-left:16px">
<h2>Responsive Topnav Example</h2>
<p>Resize the browser window to see how it works.</p>
</div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</body>
</html>
为什么它似乎不是您导航到另一个页面的原因:
当您点击“新闻”链接时,由于此锚标记#news
中的<a href="#news">News</a>
,它不会将您带到新页面。 #
中的hashtag href
指定了一个HTML元素id,窗口将滚动到该元素id。在您的情况下,它只是滚动到您的网页的顶部,因为没有任何带有id="news"
的HTML元素。所以,这一直,你实际上只是在一个唯一的页面 - “主页”页面。
当您在“新闻”页面上时,如何突出显示“新闻”:
index.html
并将其重命名为news.html
。确保这两个文件位于同一文件夹中。我们将使每个.html
文件代表您网站上的页面,因为每个页面都包含唯一内容,因此需要不同的HTML代码。index.html
和news.html
,在代码块中替换这两行:<a href="#home" class="active">Home</a>
<a href="#news">News</a>
在index.html
这个:
<a href="index.html" class="active">Home</a>
<a href="news.html">News</a>
在news.html
中有这个:
<a href="index.html">Home</a>
<a href="news.html" class="active">News</a>
在这里,请注意,当您在“主页”页面时,class="active"
现在被放置在“主页”链接上,即,当您在“新闻”页面上时,index.html
和class="active"
被放置在“新闻”链接上,即news.html
。这就是链接的绿色突出显示(根据您指定的CSS类.active)。
index.html
并尝试单击“新闻”链接。您应该导航到“新闻”页面,导航栏现在应该以绿色突出显示,如下所示:当您将屏幕调整为较小尺寸并单击汉堡菜单按钮时,它应该在“新闻”页面上显示为正确的链接,并以绿色突出显示:
提示:在每个HTML页面中复制和粘贴CSS样式都很繁琐,并且包含太多重复的代码。为了清理它,我建议你将所有的CSS样式放在一个.css
文件中,并将该文件链接到每个HTML文件。按照w3schools here的“外部CSS”部分中的说明进行操作。