首页 > 解决方案 > 试图改变css onclick中的不透明度

问题描述

尝试使 onclick 功能使不透明度从 0 变为 1,以便 .dropdown-content 在全高之前不显示。

$(".fa-bars").click(function() {
        $(".fa-times").toggle();
        $("header").css("height", "100%");
        $("header").css("transition", "height 1s ease-in");
        $("header").css("grid-template-rows", "50px 400px");
        $("header").css("grid-row-gap", "20px");
        $("header").css("grid-template-areas", "'dp logo start' 'dc dc dc'");
        $(".dropdown-content").css("display", "grid");
        $(".fa-bars").css("display", "none");
        event.preventDefault();
});

JSFiddle:https ://jsfiddle.net/lambsbaaacode/uax6oe94/24/

标签: javascriptjqueryhtmlcss

解决方案


一种方法是利用transition-delayCSS 属性和CSS 特性.dropdown-content在菜单打开后触发菜单项的可见性(内部)。

因为我们知道菜单的打开动画需要一秒钟才能完成(即height 1s ease-in),所以我们可以将菜单项的可见性延迟一秒钟以达到预期的效果。

这里的关键思想是引入一个 CSS“修饰符类”(即),它为and.open增加了更大的特异性。这个修饰符:header.dropdown-content

  • 指定标题处于“打开”状态时的样式,并且
  • .dropdown-content当标头处于打开状态时,指定后代的不透明/可见样式

在 SCSS 中,可以写成:

header {  
  transition : height 1s ease-in;

  /* Define the dropdown-content transition styles on opacity, where
  the opacity delay causes opacity of menu items to change after menu
  animation (of 1sec) is complete */
  .dropdown-content  {  
    opacity:0;
    transition-property: opacity;
    transition-duration: 0.1s;
    transition-delay: 1s;
    display:block;
  }

  /* CSS modifier class for "header.open" causes height to change
  when open class applied */
  &.open {
    height:100%;
    grid-template-rows: 50px 400px;
    grid-row-gap:20px;
    grid-template-areas:'dp logo start' 'dc dc dc';
  }

  /* When open modifier class applied to parent header, items in the
  .dropdown-content child are set to be opaque/visible */
  &.open .dropdown-content {
    opacity:1.0;
  }
}

使用上面的 SCSS,您可以将脚本简化为:

$(".fa-bars").click(function() {

    /* Add open modifier class to apply new CSS defined above and
    delay visiblity of dropdown-content content */
    $("header").addClass("open");

    $(".fa-times").toggle();
    $(".fa-bars").css("display", "none");
    event.preventDefault();
});
$(".fa-times").click(function() {

    /* Remove open modifier class to hide menu and items */
    $("header").removeClass("open");

    $(".fa-bars").toggle();
    $(".fa-times").css("display", "none");
    event.preventDefault();
});

现在,里面的菜单项只有在动画完成.dropdown-content后才可见。可以在此处找到header一个工作示例- 希望对您有所帮助!


推荐阅读