How to ensure CSS :hover is applied to dynamically added element

后端 未结 9 1055
广开言路
广开言路 2021-02-07 14:59

I have a script that adds full images dynamically over thumbnails when you hover over them. I\'ve also given the full images a CSS :hover style to make them expand to a larger w

9条回答
  •  梦如初夏
    2021-02-07 15:40

    [Edit: while my explanation might be of interest, pozs' solution above is nicer, so I suggest using that if you can.]

    The hover pseudo-class specification is quite relaxed concerning when it should be activated:

    CSS does not define which elements may be in the above states, or how the states are entered and left. Scripting may change whether elements react to user events or not, and different devices and UAs may have different ways of pointing to, or activating elements.

    In particular, it is not being activated when you update the visibility of the anchor element on load.

    You can get around this fairly easily: copy the hover styles to a class, intercept the cursor moving over the element that it will eventually cover, and based on that add or remove your class from the element.

    Demo: JS Bin (based on your delayed example).

    Javascript:

    $("#image")
      .on('mouseenter', function () {
        fullimage.attr('src',fullimageurl).toggleClass('mouseover', true);
        $(this).off('mouseenter');
      })
      .mouseleave(function() {
        fullimage.toggleClass('mouseover', false);
      });

    CSS:

    .kiyuras-image:hover, .kiyuras-image.mouseover {
        max-width: 400px;
    }

提交回复
热议问题