开发者

img src & jQuery?

I have an image, and using jQuery I've turned it into a button. The so called button has two states: regular and pushed.

Using jQuery I detect a "mousedown" and "mouseup" and replace the "src" attribute, like so:

$("#btn").click(function() {
   ;//DO SOMETHING HERE WHEN PRESSED
});
$("#btn").mousedown(function() {
   $(this).attr({ src: regular.png });
});
$("#btn").m开发者_开发问答ouseup(function() {
   $(this).attr({ src : pushed.png });
});

While testing this offline it works great! But today I noticed that when the images are stored on the server it loads the images over and over and over again with every attribute change.

How can avoid this load issue and make all the images load only once from the server?

Also, if there is a better to accomplish what I'm trying to do here, please let me know.

Thank you.


Create a single image containing both button states. Then, dynamically change the position of the background image on mouseout/mouseover:

<style type="text/css">

 .button_normal {
   width: 50px;
   height: 50px;
   background-image: url(merged_button_bg.png);
   background-repeat: no-repeat;
   border: solid black 1px;
   cursor: pointer;
 }

 .button_over {
  background-position: -50px;
 }

</style>

<div class="button_normal"></div>

<script>

 $(document).ready(function() {
  $('.button_normal').mouseover(function() {
   $(this).addClass('button_over');
  });
  $('.button_normal').mouseout(function() {
   $(this).removeClass('button_over');
  });
 });

</script>

This example assumes a target image of 50px square and merged_button_bg.png is 100px by 50px.


Instead of changing the src attribute, you could use a span or div to show the image (via a background image) and create two CSS classes, one for each image. Then you can just toggle the element's CSS class to switch buttons.


Have you tried the Preload plugin?

Update: Sorry, I didn't read carefully enough, I thought it was a rollover requirement. A more general preload script is here.

Incidentally, I agree that CSS sprites are the better solution if they are appropriate to the situation, i.e. if you have complete control over the images themselves.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜