onclickで画像を入れ替える (改訂版)

Wednesday, Jul 26, 2006 - 01:39 +09:00

以前つくったスクリプトを改造してみた。1つ前の記事の応用です。

1 2 3

HTML
  <p><img src="/other/archives/img/sample_no1.gif" alt="" id="photo" width="210"  /></p>
  <p>
    <a href="/other/archives/img/sample_no1.gif"  class="changeImg"><img src="/other/archives/img/sample_no1.gif" alt="1" width="60" /></a>
    <a href="/other/archives/img/sample_no2.gif"  class="changeImg"><img src="/other/archives/img/sample_no2.gif" alt="2" width="60" /></a>
    <a href="/other/archives/img/sample_no3.gif"  class="changeImg"><img src="/other/archives/img/sample_no3.gif" alt="3" width="60" /></a>
  </p>
Javascript
window.onload = getSrc;

function getSrc()
{
  var x = document.getElementsByTagName('a');
  for (var i=0;i<x.length;i++)
  {
    if (x[i].getAttribute('className') == 'changeImg' || x[i].getAttribute('class') == 'changeImg')
    {
      x[i].onclick = function () {
      return changeImg(this.href)
      }
    }
  }
}

function changeImg(imgSrc) {
  document.getElementById('photo').src = imgSrc;
  return false;
}

posted in Javascript Trackback (0)

Trackback

このエントリーのトラックバックURL
http://rospear.info/other/mt-tb.cgi/201

« Previous Entry - Next Entry »