下記コードにて、簡単なスライダーのようなものを作りました。
スライダー自体の動きにはなんの問題も無いのですが、ウィンドウのリサイズ行った時に、imgタグのsrcを参照してsrcの一部を変更して画像を変えるようなコードを書いたのですが、Uncaught TypeError: Cannot read property 'split' of undefined
とエラーが出て、var $imgSrc = $(this).attr('src').split('/');
の.split部分で赤線が出てしまいます。
参考サイトからヒントを得て記述いたしました。
HTML
1<div class="slide_show"> 2 <img src="https://s3-ap-northeast-1.amazonaws.com/~/catch_01_pc.png" alt="" name="catch_01"> 3 <img src="https://s3-ap-northeast-1.amazonaws.com/~/catch_02_pc.png" alt="" name="catch_02"> 4 <img src="https://s3-ap-northeast-1.amazonaws.com/~/catch_03_pc.png" alt="" name="catch_03"> 5</div>
jQuery
1$(window).on('load resize', function() { 2 if (window.matchMedia('(max-width:768px)').matches) { 3 4 var $cc_img = $('.slide_show').find('img'); 5 var $imgSrc = $(this).attr('src').split('/'); 6 7 $cc_img.each(function() { 8 if ($imgSrc[5] == 'catch_01_pc.png') { 9 var catch_sp = $(this).attr('src').replace('_pc' , '_sp'); 10 $(this).attr('src', catch_sp); 11 } 12 13 if ($imgSrc[5] == 'catch_02_pc.png') { 14 var catch_sp = $(this).attr('src').replace('_pc' , '_sp'); 15 $(this).attr('src', catch_sp); 16 } 17 18 if ($imgSrc[5] == 'catch_03_pc.png') { 19 var catch_sp = $(this).attr('src').replace('_pc' , '_sp'); 20 $(this).attr('src', catch_sp); 21 } 22 }); 23 }; 24}); 25 26$(window).on('load' , function() { 27 $('.slide_show').each(function() { 28 var $slides = $(this).find('img'), 29 slideCount = $slides.length, 30 currentIndex = 0, 31 duration = 750; 32 33 $slides.eq(currentIndex).fadeIn(duration); 34 35 setInterval(showNextSlide, 5500); 36 37 function showNextSlide() { 38 39 var nextIndex = (currentIndex + 1) % slideCount; 40 41 $slides.eq(currentIndex).fadeOut(duration); 42 43 $slides.eq(nextIndex).fadeIn(duration); 44 45 currentIndex = nextIndex; 46 } 47 }); 48}); 49
稚拙な記述で大変お恥ずかしいのですが、何かアドバイスをご教授頂けますと幸いです。
よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。