1

在 jQuery 和这个小插件的帮助下,我正在通过一些元素的颜色、背景颜色和边框颜色 css 属性进行颜色循环。

我正在这样做:

var currentColor = myRandNumber; // I get this variable from the main page
var myWebColors = [ '#49aea2', '#5da270', '#a1b144', '#ceb33d', '#ce812d',
'#c44e4e', '#ac4275', '#705f91', '#4d6791', '#5199a4' ];

window.setInterval( animateColor, 2000 ); // not using requestAnimationFrame
                                          // for browser compatibility

function animateColor() {

    $(".new-project-header, .button a:active,
    #logo, ul#menu-main-nav li a:active, ul#menu-main-nav li.contact a,
    ul#menu-main-nav li.contact a:visited, .footer-twitter,
    .footer-mail").animate(
        {
            backgroundColor: myWebColors[currentColor]
        }, "slow");

    $("a:hover, p a:hover, ul#menu-main-nav li.contact a:hover,
    h3.portfolio-item-title a:hover").animate(
        {
            color: myWebColors[currentColor]
        }, "slow");

    $("p a, p a:visited").animate(
        {
            borderColor: myWebColors[currentColor]
        }, "slow");

    if (currentColor == 9) { // the following cycles through the array
                             // in an endless loop
        currentColor = 0;
    } else {
        currentColor++;
    }
}

编辑: jsfiddle在这里

我遇到的问题是,当我将鼠标悬停在 上时p a,虽然 jQuery 的颜色循环很好,但是一旦我将鼠标移出,链接将保持在它的 :hover 状态,它循环到的最新颜色。

当我将鼠标悬停在ul#menu-main-nav li. 它会改变 a:hover颜色,当它只应用于ul#menu-main-nav li.contact. 就像后一个选择器 :hover 状态优先于前者的 css。

也许我应该用on事件手动完成所有事情?也许我应该在每个循环步骤结束时“重置”所有非 :hover 状态?也许所有这一切都是矫枉过正,我应该尝试不同的方法?

谢谢!

4

2 回答 2

1

当鼠标退出元素时,您需要将状态更改回默认值。即悬停完成。

JQuery hover 可以轻松做到这一点。

$( "a" ).hover(
  function() {
    $( this ).animate({  color: myWebColors[currentColor] }, "slow");
  }, function() {
        $( this ).animate({  color: default_color }, "slow");
  }
);

只是出于好奇,你为什么不使用这里解释的 CSS:hover 属性 http://www.w3schools.com/cssref/sel_hover.asp

于 2013-10-09T08:46:33.627 回答
0

First, you have a loop (setInterval()) that is running even if you didn't hover anything. It is useless.

So, i make an update of your Fiddle with setTimeout(). You can start from something like this. I also replaced :hover statments by event handlers. I don't know if it is ok for you. But this is how I should have done it. Hope it'll help.

于 2013-10-09T09:34:19.213 回答