我想创建一个使用锚链接的导航栏(导航栏是固定的,用户停留在一个页面上)。默认情况下,我希望导航栏中的第一个链接使用背景突出显示进行设置,以指示它已被选中。如果用户点击导航栏上的其他链接,我希望该链接被赋予选择样式。
是否有纯HTML / CSS方法来执行此操作?
编辑:我目前正在修改将导航链接转换为秘密单选按钮。如果我让它工作,我会报告。
答案 0 :(得分:0)
您可以使用:active Selector。
a:active {
background-color: yellow;
}
此样式将应用于您单击的最后一个元素...一旦失去焦点,它将不会保留样式。
如果可以的话,在我看来,通过javascript更改课程会好得多。
答案 1 :(得分:0)
您可以使用:target
并使用样式。它看起来像是:
li {
display: inline-block;
float: left;
border: 1px solid white;
}
a {
color: white;
text-decoration: none;
padding: 15px;
background-color: #bada55;
}
#targetDiv {
width: 50px;
height: 50px;
background-color: #bada55;
float: right;
border: 1px solid white;
}
:target {
background-color: purple !important;
}
<ul>
<li><a href="#first" id="first">First</a>
</li>
<li><a href="#second" id="second">Second</a>
</li>
<li><a href="#third" id="third">Third</a>
</li>
<li><a href="#targetDiv">Target</a>
</li>
<li><a href="#targetDiv" id="targetDiv">Target Div</a><li>
</ul>
stat
。
注意强>
这会干扰浏览器历史记录,因此您可能需要注意这一点。它也可以创建一个“跳跃”,但如果它是一个固定的导航,你可能会没事。小提琴在链接上有e.preventDefault()
以防止跳跃,但我认为如果没有它,你可以没事。
<强>已更新强>
添加了一个小提琴,并根据评论包含了其他div
。
答案 2 :(得分:0)
<强> CSS 强>
input[type="radio"] {
display: none;
}
input[type="radio"]:checked + a {
background: blue !important;
color: white !important;
}
<强> HTML 强>
<input type="radio" id="x" name="selectedLink" checked />
<a href="#associatedAnchor1" onclick="document.getElementById('x').checked = true">
This is a link that will apply 'selected' style to itself and
strip the 'selected style from all other links in its group
</a>
<input type="radio" id="y" name="selectedLink" />
<a href="#associatedAnchor2" onclick="document.getElementById('y').checked = true">
This is a link that will apply 'selected' style to itself and
strip the 'selected style from all other links in its group
</a> <!-- and so on -->
它使用 tiny 数量的JavaScript,但它最接近可能存在的答案。希望它对某人有用! :)