三个选择:
第一个 - CSS3
如果您不关心supporting all browsers,请使用此方法。它是纯 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*/ }
}
(如果您想摆脱所有那些丑陋的前缀规则,请查看PrefixFree)。
第二个——jQuery
>
如果您确实关心旧版浏览器的支持,请使用此选项。在您的页面中包含 jQuery,首先将其插入您的 head:
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type = "text/javascript"></script>
然后:
$(".yourlink").click(function() {
$("#yourdivid").css("background", "red").delay(1000).css("background", "white");
};
请注意,此 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);
};
希望对您有所帮助!