开发者

jquery slide down image on page load

开发者 https://www.devze.com 2022-12-28 00:37 出处:网络
I\'m not experienced with jquery (or java script really), but trying to make an image (img id=mike ...) slide in when a page loads.

I'm not experienced with jquery (or java script really), but trying to make an image (img id=mike ...) slide in when a page loads.

After looking through the jquery docs and trying Google queries, I have so far come up with this

  $(document).ready(function() {

$("#mike").load(function () {
      $(this).show("slide", { direction: "up" }, 2000);

});

  });

And applied the CSS displa开发者_如何转开发y:hidden so it remains hidden until I want it to slide in on page load.

This doesn't seem to work unless I reload the page though.

Hoping someone could help me out with this please :)


.load() isn't triggered if the image is retrieves from cache, depending on the browser, so you need to manually fire the event if the image is complete, like this:

$(function() {
  $("#mike").one('load', function () {
    $(this).show("slide", { direction: "up" }, 2000);
  }).each(function() {
    if(this.complete) $(this).load();
  });
});

The .one() ensures the event only fires once. The .each() loops though each element, only one in this case, and if it's already complete (which it would be if fetched from cache) fires the event to make sure it goes off (if it already fired, the .one() took care of it not sliding in twice).


@Dean, you'll probably be best off using a combination of CSS and jQuery to do the job--this is to get around caching issues with images (see Nick's response for an explanation). Here's a rough example:

CSS:

#mike {
    display: block;
    margin: 0; padding: 0; /* Ignore this if you're using a reset.css */

    position: absolute;    /* Change this to relative based on the containing elements */
    top: 2000px;           /* Assumes you have an image that's 100px tall as an example */
}

jQuery:

jQuery( function(){
    $('#mike').animate({'top':'0'},255,'linear', function(){
        console.log('Done Animation);
    });
} );

You can also delay the animation a few seconds (or milliseconds) after page load:

jQuery( function(){
    // Delay the animation by 1 second after page load before animating.
    $('#mike').delay(1000).animate({'top':'0'},255,'linear', function(){
        console.log('Done Animation);
    });
} );
0

精彩评论

暂无评论...
验证码 换一张
取 消