CSS3 Element with Opacity:0 (invisible) responds to mouse events

后端 未结 3 796
执念已碎
执念已碎 2021-02-19 03:33

CSS3 using Webkit in Safari; I have a button that, when clicked, causes a div to fade in. That div is just a big filled rectangle and it has a few buttons in it, one of whichcau

3条回答
  •  [愿得一人]
    2021-02-19 04:28

    A clean(er?) solution for the problem you are having - which is a common problem for things like tooltips and modal popups with a 'fade-in' effect - is to not only transition between opacity, but also the "visibility" property. Unlike 'display', 'visibility' is an actual animatable property, and it will do the right thing in that it makes the element invisible (and non-responsive to input events) only before a transition begins, and only after a transition returns to the initial state.

    The previously given answer does work, but depends on JavaScript to manipulate properties which may be less desirable. By having all this done through pure CSS, your JavaScript has to do nothing other than set and unset a class on the element that needs to be shown. If you're creating a tooltip, it can be done without any JS at all by making the tooltip a child element and using the 'hover' pseudo-selector on the parent.

    So for for a popup triggered by clicking on something, you would style it like so:

    #popup
    {
      /* ...cosmetic styling, positioning etc... */
    
      -webkit-transition: all 0.2s ease-in-out 0s;
      -moz-transition: all 0.2s ease-in-out 0s;
      -ms-transition: all 0.2s ease-in-out 0s;
      transition: all 0.2s ease-in-out 0s;
    
      opacity: 0;
      visibility: hidden;
    }
    
    #popup.shown
    {
      opacity: 1;
      visibility: visible;
    }
    

    Then your JavaScript can simply toggle the "shown" class.

    A live example: http://jsfiddle.net/y33cR/2/

提交回复
热议问题