jQuery dynamic image loading

后端 未结 1 948
遥遥无期
遥遥无期 2021-01-23 04:47

**I try to load an image when I type a reference in an input.




    
        

        
相关标签:
1条回答
  • 2021-01-23 05:23

    You should go ahead and cache the image (pre-load it into a variable) so that you can access it quickly. You also might want to make use of jQuery's load() function to tell you when the image has been loaded. Here's a quick example:

    var theCachedImage = new Image();
    /* Boolean that tells us whether or not the image has finished loading. */
    var theBoolean;
    $(theCachedImage).load(function () {
        In this callback, the image has finished loading.Set "theBoolean"
        to true.
        theBoolean = true;
    });
    theCachedImage.src = "your/image/source";
    

    Like Kevin mentioned, the fadeIn is working. There's just nothing to fade in.

    EDIT:

    In your keyUp function, simply check the value of the conditional boolean and perform actions accordingly. Example:

    $('#id').keyup(function () {
        if (theBoolean) {
            $('#img').html('<img src="http://www.site.com/' + $(this).val() + '.jpg"
    width="200px">');
            $('#img').hide().fadeIn('slow');
        } else {
            /* Your image hasn't been loaded yet. Do something to let the user know
             * or figure out the appropriate action to take. */
        }
    });
    
    0 讨论(0)
提交回复
热议问题