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

后端 未结 9 1049
广开言路
广开言路 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:44

    You could do something like that : http://jsfiddle.net/jR5Ba/5/

    In summary, append a loading layout in front of your image, then append a div containing your large image with a .load() callback to remove your loading layer.

    The fiddle above has not been simplified and cleaned up due to lack of time, but I can continue to work on it tomorrow if needed.

    $imageContainer = $("#image-container");    
    $image = $('#image');
    
    $imageContainer.on({
        mouseenter: function (event) {    
           //Add a loading class
           $imageContainer.addClass('loading');
           $image.css('opacity',0.5); 
    
           //Insert div (for styling) containing large image            
           $(this).append('
    '); //Append large image load callback $('#'+this.id+'-large').load(function() { $imageContainer.removeClass('loading'); $image.css('opacity',1); $(this).slideDown('slow'); //alert ("The image has loaded!"); }); }, mouseleave: function (event) { //Remove loading class $imageContainer.removeClass('loading'); //Remove div with large image $('#'+this.id+'-large').remove(); $image.css('opacity',1); } });

    EDIT

    Here is a new version of the fiddle including the right size loading layer with an animation when the large picture is displayed : http://jsfiddle.net/jR5Ba/6/

    Hope it will help

提交回复
热议问题