单击锚点时突出显示div

nxe*_*xet 13 html css jquery class onclick

我发现自己坚持这个:

我有一个指向<a>内部的锚链接div,因此页面一直向下滚动到它.

不幸的是,div它位于页面的底部,因此用户很可能看不到它.

我认为解决这个问题的好方法是在点击链接时更改div的类,例如将边框颜色切换为红色,然后在2秒内淡出恢复正常.

我不知道如何做到这一点.我用Google搜索,似乎可以用jQuery完成,但我真的不明白如何根据我的需要编辑脚本.

非常感谢!

Pra*_*man 10

是的,您可以通过两种方式进行黄色褪色技巧:

使用:target伪类:

<section id="voters"> 
   Content
</section>
Run Code Online (Sandbox Code Playgroud)

各自的CSS

:target {
   background: yellow;
}
Run Code Online (Sandbox Code Playgroud)

使用黄色渐变技术

在点击功能中,如果有,您可以这样做:

$('a[href*="#"]').click(function(){
    $($(this).attr("href")).effect("highlight", {}, 1500);
});
Run Code Online (Sandbox Code Playgroud)

或使用animate():

$('a[href*="#"]').click(function(){
    $($(this).attr("href")).animate({"background-color": "#ffc"}).delay(2000).animate({"background-color": "transparent"});
});
Run Code Online (Sandbox Code Playgroud)

小提琴:http://jsfiddle.net/HnERh/

PS:对于使用 effect(),你需要有这两个JS: effects.core.js effects.highlight.js.


Chr*_*ris 9

三种选择:

第一个 - CSS3

如果您不关心支持所有浏览器,请使用此方法.这是纯CSS,所以这是一个优势.这是一个大纲(包括多个浏览器的多个版本的规则):

.youranchorsclass:active ~ #yourdivsid { /*when the anchor is active (clicked)*/
   -moz-animation: myanimation 1s;
   -webkit-animation: myanimation 1s;
   -o-animation: myanimation 1s;
   animation: myanimation 1s;
}
@-moz-keyframes myanimation, @-webkit-keyframes myanimation, @-o-keyframes myanimation, @keyframes myanimation {
   from { background: red; }
   to { background: white; /*or whatever it was originally*/ }
}
Run Code Online (Sandbox Code Playgroud)

(如果你想摆脱所有那些丑陋的前缀规则,请看看PrefixFree).

第二个 - jQuery

如果您关心旧浏览器支持,请使用此选项.在您的页面中包含jQuery,首先将其插入到您的head:

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type = "text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

然后:

$(".yourlink").click(function() {
   $("#yourdivid").css("background", "red").delay(1000).css("background", "white");
};
Run Code Online (Sandbox Code Playgroud)

请注意,这个jQuery方法不会逐渐改变颜色,你必须包含一个插件(如jQuery UI)才能这样做.

第三个 - 纯JavaScript

如果您不想仅为这么小的效果包含一个相对较大的库,请使用此选项.它非常简单,这是一个让你入门的评论大纲:

function changeDivColor(color) {
    document.getElementById("yourdivid").style.backgroundColor = color;
}
document.getElementById("youranchor").onClick = function() { //when the anchor is clicked
    changeDivColor("red"); //chang the div color to red
    setTimeout(function() { //wait 1000 milliseconds (1s) -- see below
        changeDivColor("white"); //then change it back to white
    }, 1000);
};
Run Code Online (Sandbox Code Playgroud)

希望以任何方式帮助!