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

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

    I'm not 100% sure why the :hover declaration is only triggered on slight mouse move. A possible reason could be that technically you may not really hover the element. Basically you're shoving the element under the cursor while it is loading (until the large image is completely loaded the A element has display: none and can therefore impossible be in the :hover state). At the same time, that doesn't explain the difference with smaller images though...

    So, a workaround is to just use JavaScript and leave the :hover statement out of the equation. Just show the user the two different IMG elements depending on the hover state (toggles in JavaScript). As an extra advantage, the image doesn't have to be scaled up and down dynamically by the browser (visual glitch in Chrome).

    See http://jsbin.com/ifitep/34/

    UPDATE: By using JavaScript to add an .active class on the large image, it's entirely possible to keep using native CSS animations. See http://jsbin.com/ifitep/48

    0 讨论(0)
  • 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;
    }
    0 讨论(0)
  • 2021-02-07 15:41

    If the selectors are correct, CSS will be applied to all elements, dynamic or otherwise. This includes all pseudo classes, and will change as attributes in the DOM change.

    0 讨论(0)
  • 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('<div><img class="hidden large-image-container" id="'+this.id+'-large" src="'+fullimageurl+'" /></div>');
    
           //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

    0 讨论(0)
  • 2021-02-07 15:46

    From this part of your question: "This works fine if the image loads quickly or is cached, but if the full image takes a long time to load and you don't move the mouse while it's loading,"

    Could it be worth while to "preload" all of the images first with JavaScript. This may allow all of the images to load successfully first, and it may be a little more user friendly for people with slower connections.

    0 讨论(0)
  • 2021-02-07 15:49

    TL;DR: You cannot rely on :hover applying to dynamically added elements underneath the cursor. However, there are workarounds available in both pure CSS and Javascript.

    I'm upvoting both Jordan Gray and posz' answers, and I wish I could award them both the bounty. Jordan Gray addressed the issue re: the CSS specification in a somewhat conclusive way and offered (another) working fix that still allowed for :hover and other CSS effects like transitions, except on load. posz provided a solution that works even better and avoids Javascript for any of the hover events; I provide essentially the same solution here, but with a div instead of a span. I decided to award it to him, but I think Jordan's input was essential. I'm adding and accepting my own answer because I felt the need to elaborate more on all of this myself. (Edit: Changed, I accepted posz')

    Jordan referenced the CSS2 spec; I will refer instead to CSS3. As far as I can tell, they don't differ on this point.

    The pseudo-class in question is :hover, which refers to elements that the user has "designated with a pointing device." The exact definition of the behavior is deliberately left vague to allow for different kinds of interaction and media, which unfortunately means that the spec does not address questions like: "Should a new element that appears under the pointing device have this pseudo-class applied?" This is a hard question to answer. Which answer will align with user intent in a majority of cases? A dynamic change to a page the user is interacting with would normally be a result of ongoing user interaction or preparation for the same. Therefore, I would say yes, and most current browsers seem to agree. Normally, when you add an element under the cursor, :hover is immediately applied. You can see this here: The jsbin I originally posted. Note that if there's a delay in loading the larger image, you may have to refresh the page to get it to work, for reasons I'll go into.

    Now, there's a similar case where the user activates the browser itself with the cursor held stationary over an element with a :hover rule; should it apply in that case? The mouse "hover" in this case was not a result of direct user interaction. But the pointing device is designating it, right? Besides, any movement of the mouse will certainly result in an unambiguous interaction. This is a harder question to answer, and browsers answer it in different ways. When you're activating them, Chrome and Firefox do not change :hover state until you move the mouse (Even if you activated them with a click!). Internet Explorer, on the other hand, updates :hover state as soon as it's activated. In fact, it updates it even when it's not active, as long as it's the first visible window under the mouse. You can see this yourself using the jsbin linked above.

    Let's return to the first case, though, because that's where my current issue arises. In my case, the user hasn't moved the mouse for a significant length of time (over a second), and an element is added directly underneath the cursor. This could more easily be argued to be a case where user interaction is ambiguous, and where the pseudo-class should not be toggled. Personally, I think that it should still be applied. However, most browsers do not seem to agree with me. When you hover over the image for the first time and then do not move your mouse in this jsbin (Which is the one I posted in my question to demonstrate the issue, and, like the first one, has a straightforward :hover selector), the :hover class is not applied in current Chrome, Opera, and IE. (Safari also doesn't apply it, but interestingly, it does if you go on to press a key on the keyboard.) In Firefox, however, the :hover class is applied immediately. Since Chrome and Firefox were the only two I initially tested with, I thought this was a bug in Chrome. However, the spec is more or less completely silent on this point. Most implementations say nay; Firefox and I say aye.

    Here are the relevant sections of the spec:

    The :hover pseudo-class applies while the user designates an element with a pointing device, but does not necessarily activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not that do not support interactive media do not have to support this pseudo-class. Some conforming user agents that support interactive media may not be able to support this pseudo-class (e.g., a pen device that does not detect hovering).

    [...]

    Selectors doesn't define if the parent of an element that is ‘:active’ or ‘:hover’ is also in that state.

    [...]

    Note: If the ‘:hover’ state applies to an element because its child is designated by a pointing device, then it's possible for ‘:hover’ to apply to an element that is not underneath the pointing device.

    So! On to the workarounds! As several have zealously pointed out in this thread, Javascript and jQuery provide solutions for this as well, relying on the 'mouseover' and 'mouseenter' DOM events. I explored quite a few of those solutions myself, both before and after asking this question. However, these have their own issues, they have slightly different behavior, and they usually involve simply toggling a CSS class anyway. Besides, why use Javascript if it's not necessary?

    I was interested in finding a solution that used :hover and nothing else, and this is it (jsbin). Instead of putting the :hover on the element being added, we instead put it on an existing element that contains that new element, and that takes up the same physical space; in this case, a div containing both the thumbnail and the new larger image (which, when not hovered, will be the same size as the div and thumbnail). This would seem to be fairly specific to my use case, but it could probably be accomplished in general using a positioned div with the same size as the new element.

    Adding: After I finished composing this answer, pozs provided basically the same solution as above!

    A compromise between this and one of the full-Javascript solutions is to have a one-time-use class that will effectively rely on Javascript/DOM hover events while adding the new element, and then remove all that and rely on :hover going forward. This is the solution Jordan Gray offered (Jsbin)

    Both of these work in all the browsers I tried: Chrome, Firefox, Opera, Safari, and Internet Explorer.

    0 讨论(0)
提交回复
热议问题