Hatena::Groupkakisute

g5nの書き殴り

2007-12-10

rollover.js改

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

rel 属性にロールオーバー用の画像を指定できたほうがいいという話が出たのでしてみた。

使い方

<head>
  <!-- ... -->
  <script type="text/javascript" src="prototype.js"></script>
  <script type="text/javascript" src="rollover.js"></script>
  <!-- ... -->
</head>
<body>
  <!-- ... -->

  <a class="rollover" rel="rollover[../img/over.gif]"><img src="../img/default.gif"></a>

  <!-- ... -->

rollover.js

var preloaded_images = $A();

function init_rollover()
{
  var toggle = function(img, original, another){
    return function(){
      if (img.src == original) {
        img.src = another;
      } else {
        img.src = original;
      }
    }
  };

  var preload = function(img, another){
    var holder = new Image();
    holder.src = another;
    preloaded_images.push(holder);
  };

  var buttons = $$('.rollover');

  buttons.each(function(button){
    var img = button.getElementsByTagName("img")[0];
    var rel = button.readAttribute("rel");
    if(img){
      var another = "";
      var original = img.src;
      if (rel && rel.match(/rollover\[(.*)\]/)) {
        another = RegExp.$1;
      } else {
        if (img.src.match(/_on\./)){
          another = img.src.sub(/_on\.(png|gif|jpg)$/, "_off.#{1}");
        } else {
          another = img.src.sub(/_off\.(png|gif|jpg)$/, "_on.#{1}");
        }
      };

      preload(img, another);
      button.onmouseover = toggle(img, original, another);
      button.onfocus = toggle(img, original, another);
      button.onmouseout = toggle(img, original, another);
      button.onblur = toggle(img, original, another);
    }
  });
}

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