0

我正在尝试构建一个在点击时淡入淡出的菜单。这是代码:

HTML

<div id="trigger">CLICK</div>

<ul data-status="shown" id="navi">
  <li><a href="#">Link</a></li>
  <li><a href="#">Link</a></li>
</ul>

CSS

@keyframes fade {
    0% { opacity: 0; }
    100% { opacity: 1; display: block; }
}

ul {
  background: grey;
}

ul[data-status="shown"] {
   opacity: 1;
   animation: fade 2s;
}

ul[data-status="hidden"] {
    opacity: 0;
    animation: fade 2s;
    animation-direction: reverse;
}

ul[data-status="removed"] {
    display: none;
}

JavaScript

function myMenu () {
    var trigger = document.getElementById( 'trigger' ),
        menu = document.getElementById( 'navi' ),
        state = menu.getAttribute( 'data-status' );

    if ( state == 'shown' ) {
        menu.removeAttribute( 'data-status' );
        menu.setAttribute( 'data-status', 'removed' );
        state = menu.getAttribute( 'data-status' );
    }

    var toggle = function () {
        if ( state == 'shown' ) {
            menu.removeAttribute( 'data-status' );
            menu.setAttribute( 'data-status', 'hidden' );
            setTimeout( function() {
                menu.removeAttribute( 'data-status' );
                menu.setAttribute( 'data-status', 'removed' );
                state = menu.getAttribute( 'data-status' );
            }, 2000 );
        }

        if ( state == 'removed' ) {
            menu.removeAttribute( 'data-status' );
            menu.setAttribute( 'data-status', 'shown' );
            state = menu.getAttribute( 'data-status' );
        }
    };

    trigger.addEventListener( 'click', toggle, false );

}

myMenu();

示例:http: //jsbin.com/avUWUnO/1/edit

淡入按预期工作,但实际上不存在淡出,菜单只是消失了。或者这可能是因为我点击太快了?然后那里有一些奇怪的延迟,错误可能是我使用的地方setTimeout,但我无法发现那里有什么问题。

状态设置为隐藏,CSS 动画触发,两秒后动画结束,菜单被移除。为什么这没有按预期工作?

4

1 回答 1

1

You're missing the vendor prefixes in the css properties. I changed any and all animation and keyframe selectors and added -webkit- (chrome and safari) and it worked.

Vendor prefixes are -webkit- (safari, and chrome < 27 I think), -o- is opera < 17, IE10 is the first browser to nix vendor prefixes so you don't have to worry about that, and -moz- is firefox. Be sure to include both the prefixed version and the non prefixed version.

So for instance, I only changed -webkit-:

@-webkit-keyframes fade {
  0% { opacity: 0; }
  100% { opacity: 1; display: block; }
}

@keyframes fade {
  0% { opacity: 0; }
  100% { opacity: 1; display: block; }
}

ul {
  background: grey;
}

ul[data-status="shown"] {
 opacity: 1;
 -webkit-animation: fade 2s;
 animation: fade 2s;
}

ul[data-status="hidden"] {
  opacity: 0;
  -webkit-animation: fade 2s;
  -webkit-animation-direction: reverse;
  animation: fade 2s;
  animation-direction: reverse;
}

ul[data-status="removed"] {
  display: none;
}

But you may also want to add the rest of the prefixes.

JSBin (thanks to Zeaklous for this.)

于 2013-10-19T13:48:36.870 回答