当用户通过 www.example.com/#div4 访问网站时,我希望网址中指定的分部用#F37736
(橙色)突出显示,然后在2秒内平滑过渡回#00A087
(默认颜色)。
div
要突出显示为“{navner-bar”的class
。
我尝试了什么:
var hash = false;
checkHash();
function checkHash(){
if(window.location.hash != hash) {
hash = window.location.hash;
} t=setTimeout("checkHash()",400);
};
答案 0 :(得分:6)
您可以查找哈希值,然后通过它的类名来定位除法。您立即将div
的颜色更改为橙色,然后将其设置为默认颜色。
您需要包含jQuery Color library来设置background-color
的动画,因为vanilla jQuery无法为background-color
制作动画。您也可以使用jQuery UI's highlight effect,因为UI库的大小有点重。
$(document).ready(function () {
var hash = window.location.hash;
$('.' + hash).css('background-color', '#F37736').animate({
backgroundColor: '#00A087'
}, 2000);
});
答案 1 :(得分:1)
这可以通过使用 :target
伪类的 CSS 解决。它允许您突出显示 ID 与 URL 中的哈希匹配的项目。一个非常简单的例子是:
div {
background-color: #00A087;
}
div:target {
background-color: #F37736;
}
默认情况下,div
将具有默认颜色,但在找到匹配项时,它会切换到不同的颜色。要使其按照您指定的方式工作,只需撒上一些 animation
魔法:
div {
background-color: #00A087;
}
div:target {
background-color: #F37736;
animation-delay: 2s;
animation-fill-mode: forwards;
animation-duration: 4s;
animation-name: highlight;
animation-timing-function: ease-in-out;
}
@keyframes highlight {
from {
background-color: #F37736;
}
to {
background-color: #00A087;
}
}
这里我将动画设置为延迟 2 秒并保持动画的最终状态。
使用各种可用的属性,您可以混合和匹配以使其工作方式略有不同,但这将实现问题中的要求。
答案 2 :(得分:0)
我假设你想要突出某些事件的背景颜色。 尝试将此css添加到您的代码中。这将突出显示悬停时的背景颜色。
.fixed-nav-bar {
background-color: #f37736;
}
.fixed-nav-bar:hover {
background-color: #00a087;
-webkit-transition: background-color 2000ms linear;
-moz-transition: background-color 2000ms linear;
-o-transition: background-color 2000ms linear;
-ms-transition: background-color 2000ms linear;
transition: background-color 2000ms linear;
}
希望这会对你有所帮助。