Hatena::Groupkakisute

g5nの書き殴り

2007-11-19

rollover.js

02:30 |  rollover.js - g5nの書き殴り を含むブックマーク はてなブックマーク -  rollover.js - g5nの書き殴り

車輪の再発明。要 prototype.js 1.5。

使い方

<head>
  <!-- ... -->
  <script type="text/javascript" src="prototype.js"></script>
  <script type="text/javascript" src="rollover.js"></script>
  <!-- ... -->
</head>
<body>
  <!-- ... -->
  <a class="rollover"><img src="foo_off.jpg"></a>
  <a class="rollover"><img src="bar_off.jpg"></a>
  <a class="rollover"><img src="baz_off.jpg"></a>
  <a class="rollover"><img src="qux_off.jpg"></a>
  <!-- ... -->

rollover.js

var preloaded_images = $A();

function init_rollover()
{
  var toggle = function(img){
    return function(){
      if (img.src.match(/_on\./)){
        img.src = img.src.sub(/_on\.(png|gif|jpg)$/, "_off.#{1}");
      } else {
        img.src = img.src.sub(/_off\.(png|gif|jpg)$/, "_on.#{1}");
      }
    }
  };

  var preload = function(img){
    var holder = new Image();
    if (img.src.match(/_on\./)){
      holder.src = img.src.sub(/_on\./, "_off.#{1}");
    } else {
      holder.src = img.src.sub(/_off\./, "_on.#{1}");
    }
    preloaded_images.push(holder);
  };

  var buttons = $$('a.rollover');
  buttons.each(function(button){
    var img = button.getElementsByTagName("img")[0];
    if(img){
      preload(img);
      button.onmouseover = toggle(img);
      button.onfocus = toggle(img);
      button.onmouseout = toggle(img);
      button.onblur = toggle(img);
    }
  });
}

Event.observe(window, "load", init_rollover, false);