イベントが発生した要素を取得

イベントが発生した要素を取得

  • サムネイルをホバーしたとき
  • メイン画像の「src」と「attr」の値を取得して
  • 指定された値に置き換える(スワップイメージ)

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>マウスによる画像置換</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
  <p><img src="img/00.jpg" alt="" id="mainImg"></p>
  <ul class="gallery">
    <li><img src="img/01.jpg" alt="サーフィンの画像1" id="01"></li>
    <li><img src="img/02.jpg" alt="サーフィンの画像2" id="02"></li>
    <li><img src="img/03.jpg" alt="サーフィンの画像3" id="03"></li>
    <li><img src="img/04.jpg" alt="サーフィンの画像4" id="04"></li>
    <li><img src="img/05.jpg" alt="サーフィンの画像5" id="05"></li>
  </ul>
</div><!-- /.container -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function(){
  const main = $('#mainImg');

  $('#01').hover(function(){
    main.attr('src', 'img/01.jpg').attr('alt', 'サーフィンの画像1');
  }, function(){
    main.attr('src', 'img/00.jpg').attr('alt', 'カバー');
  });
  $('#02').hover(function(){
    main.attr('src', 'img/02.jpg').attr('alt', 'サーフィンの画像2');
  }, function(){
    main.attr('src', 'img/00.jpg').attr( 'alt', 'カバー');
  });
  $('#03').hover(function(){
    main.attr('src', 'img/03.jpg').attr('alt', 'サーフィンの画像3');
  }, function(){
    main.attr('src', 'img/00.jpg').attr( 'alt', 'カバー');
  });
  $('#04').hover(function(){
    main.attr('src', 'img/04.jpg').attr('alt', 'サーフィンの画像4');
  }, function(){
    main.attr('src', 'img/00.jpg').attr( 'alt', 'カバー');
  });
  $('#05').hover(function(){
    main.attr('src', 'img/05.jpg').attr('alt', 'サーフィンの画像5');
  }, function(){
    main.attr('src', 'img/00.jpg').attr( 'alt', 'カバー');
  });
});
</script>
</body>
</html>

《style.css

@charset "URF-8";

/* -------------------------------------------
  reset
------------------------------------------- */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
ul, li {
  list-style: none;
}
a {
  color: inherit;
  text-decoration: none;
}
img {
  max-width: 100%;
  vertical-align: bottom;
}


/* ------------------------------------------
  body
------------------------------------------- */
body {
  color: #333;
  font-size: 16px;
  font-family: 
    /* "Helvetica Neue", */
    /* Arial, */
    "Hiragino Kaku Gothic ProN",
    "Hiragino Sans",
    Meiryo,
    sans-serif;
  line-height: 1.0;
}


/* -------------------------------------------
  layout
------------------------------------------- */
.container {
  max-width: 540px;
  margin: 50px auto;
  text-align: center;
}
  .container p {
    margin-bottom: 10px;
    border: 12px solid #fff;
    box-shadow: 0 0 6px #aaa;
  }
  .gallery {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
  }