简体   繁体   中英

how to change sprite position dynamically?

this is a sprite i found

在此处输入图片说明

.common-spinner.common-spinner-40x55 {
    height: 55px;
    width: 40px;
}

.common-spinner {
    background: url("images/loading-sprite.png") no-repeat scroll 100% 100% transparent;
}

<div class="loading">
<div class="common-spinner common-spinner-40x55" style="background-position: 0px 0px;"></div>
</div>

any idea how to build the loading animation from this? i tried to change position using a for loop like

for(i=0; i<=720;) {
    $('.common-spinner').css('background-position', '-'+i+'px 0px');
    i=i+20;
}

but i can not see any animation maybe because its going too fast?

any idea how to do this?

Regards

Ive added the code to jsfiddle with Erik Hesselink solution

http://jsfiddle.net/X7tGb/

To actually see the animation, you have to leave the Javascript execution thread. This can be done by using timeouts. Something like:

function setBgPosition (px)
{
  return function ()
  {
    $('.common-spinner').css('background-position', '-' + px + 'px 0px');
    if (px < 720) setTimeout(setBgPosition(px + 20), 100);
  }
}

setTimeout(setBgPosition(0), 100);

http://addyosmani.com/blog/jquery-sprite-animation/

You may want to try Google there are a ton of results regarding JavaScript sprite animation. The above is one of those results with a working demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM