【问题标题】:Different styles for an element based on the current anchor基于当前锚点的元素的不同样式
【发布时间】:2017-12-03 22:10:21
【问题描述】:
在我的 index.html 中,我有 3 个链接作为锚点。而且我还有一个固定位置的 div 元素。
<a href="#1">1</a>
<a href="#2">2</a>
<a href="#3">3</a>
<div></div>
如何根据当前的 href 自定义 div 元素?使用“id”和“target”,我只能为两个 href 执行此操作。例如:第一页的元素是红色的,第二页的元素变成绿色的,第三页的元素变成蓝色的。这可能吗?
【问题讨论】:
标签:
html
css
anchor
href
target
【解决方案1】:
是的,这是可能的。如果您收听 onhashchange 事件,则可以更改 DOM 以符合您的要求。
这是一个工作示例:
window.onhashchange = function() {
var el = document.getElementById('bar');
switch (window.location.hash) {
case '#1':
el.className = 'red';
break;
case '#2':
el.className = 'green';
break;
case '#3':
el.className = 'blue';
break;
}
}
#bar {
width: 100vw;
height: 10vh;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
<a href="#1">1</a>
<a href="#2">2</a>
<a href="#3">3</a>
<div id="bar"></div>