「jQuery」.toggleでクリックする毎に画像を切り替える

2022年2月19日

書式
$(セレクタ名).toggle(function(){処理コード},
function(){処理コード}
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#cft").toggle(function(){
$(this).attr('src', 'sample02.png');
},
function(){
$(this).attr('src', 'sample01.png');
});
});
</script>
</head>
<body>
<img src="sample01.png" id="cft">
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $("#cft").toggle(function(){ $(this).attr('src', 'sample02.png'); }, function(){ $(this).attr('src', 'sample01.png'); }); }); </script> </head> <body> <img src="sample01.png" id="cft"> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
  $("#cft").toggle(function(){
    $(this).attr('src', 'sample02.png');
  },
  function(){
    $(this).attr('src', 'sample01.png');
  });
});
</script>
</head>
<body>
  <img src="sample01.png" id="cft">
</body>
</html>

結果
.toggle() を使って画像を切り替えります。

jQuery

Posted by arkgame