jquery slide down image on page load

情到浓时终转凉″ 提交于 2019-12-23 01:19:20

问题


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 display: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 :)


回答1:


.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).




回答2:


@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);
    });
} );


来源:https://stackoverflow.com/questions/2674464/jquery-slide-down-image-on-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!