如何突出显示URL中哈希的特定div?

Kev*_*mtk 4 html javascript jquery

当用户通过www.example.com/#div4访问网站时,我希望URL中指定的分区用#F37736(橙色)突出显示,然后在2秒内平滑过渡回#00A087(默认颜色).

div被突出显示为class"固定导航栏".

我尝试过的:

var hash = false; 
checkHash();

function checkHash(){ 
  if(window.location.hash != hash) {
    hash = window.location.hash; 
  } t=setTimeout("checkHash()",400); 
};
Run Code Online (Sandbox Code Playgroud)

cch*_*ana 8

这可以通过使用伪类的 CSS 来解决:target。它允许您突出显示 ID 与 URL 中的哈希值匹配的项目。一个非常简单的例子是:

div {
    background-color: #00A087;
}
div:target {
   background-color: #F37736;
}
Run Code Online (Sandbox Code Playgroud)

默认情况下,adiv将具有默认颜色,但在找到匹配项时,它会切换为不同的颜色。为了让它按照你指定的方式工作,只需施一点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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里我将动画设置为延迟 2 秒并保持动画的最终状态。

通过各种可用的属性,您可以混合和匹配以使其工作方式略有不同,但这将实现问题中所要求的内容。

CodePen 上的示例


Mic*_*yen 6

您可以查找哈希值,然后通过它的类名来定位除法.您将立即将颜色更改为div橙色,然后将其设置为默认颜色.

您需要包含jQuery Color库来设置动画background-color,因为vanilla jQuery无法设置动画background-color.你也可以使用jQuery UI的高亮效果,认为UI库的大小有点重.

$(document).ready(function () {
    var hash = window.location.hash;
    $('.' + hash).css('background-color', '#F37736').animate({
        backgroundColor: '#00A087'
    }, 2000);
});
Run Code Online (Sandbox Code Playgroud)