IT戦記

プログラミング、起業などについて書いているプログラマーのブログです😚

JS でロールオーバー

(ネタです><)

自分も書いてみた

(function(load) {
  try {
    window.addEventListener("load", load, false);
  } catch(e) {
    window.attachEvent("onload", load);
  }
})(function() {
  var images = document.getElementsByTagName("img");
  for(var i = 0, l = images.length; i < l; i++) {
    (function(image, result) {
      if(result) {
        var onover = function() { image.src = result[1] + '_on' + result[2] }
        var onout = function() { image.src = result[1] + '_off' + result[2] }
        try {
          image.addEventListener('mouseover', onover, false);
          image.addEventListener('mouseout', onout, false);
        } catch(e) {
          image.attachEvent('onmouseover', onover);
          image.attachEvent('onmouseout', onover);
        }
        var unload = function() {
          try {
            image.removeEventListener('mouseover', onover, false);
            image.removeEventListener('mouseout', onout, false);
          } catch(e) {
            image.detachEvent('onmouseover', onover);
            image.detachEvent('onmouseout', onover);
          }
          try {
            window.removeEventListener('unload', unload, false);
          } catch(e) {
            window.detachEvent('onunload', unload);
          }
        };
        try {
          window.addEventListener('unload', unload, false);
        } catch(e) {
          window.attachEvent('onunload', unload);
        }
      }
    })(images[i], /^(.+)_off(\..)$/.test(image.src))
  }
  try {
    window.removeEventListener("load", arguments.callee, false);
  } catch(e) {
    window.detachEvent("onload", arguments.callee);
  }  
})

もはや何のコードか分からなくなってしまった

世の中には知らないほうがいいこともあるんだ><
いろいろ知る前のほうが素直なコードを書けた気がする。