onclick和删除时如何更改图像src

时间:2019-06-17 07:29:20

标签: javascript jquery css

当点击“ .swiper-slide”时,addClass('selected')

onclick svg-img1、2、3时,我可以更改img src

但是我希望图像恢复为默认的img src。当我单击其他滑动幻灯片时。

$('.swiper-slide').on('click', function() {
    $('.swiper-slide').removeClass('selected');
	$(this).addClass('selected');
   	});

jQuery(document).ready(function($) {
    $('#swi-image1').on({
	    'click':function() {
		    if($('#svg-img1').hasClass("selected")) {
			    $('#svg-img1').attr('src','/img/front/photos-white.svg');
			} else {
			    $('#svg-img1').attr('src','/img/front/photos.svg');
			}
		}
	});

	$('#swi-image2').on({
		'click':function() {
			$('#svg-img2').attr('src','/img/front/youtube-white.svg');
		}
    });
});
      
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="swiper-container pt-2 pb-4" id="contents-swiper">
	<div class="swiper-wrapper">
		<div class="swiper-slide" id="swi-img1"><img src="/img/front/photos.svg" id="svg-img1">card</div>
		<div class="swiper-slide" id="swi-img2"><img src="/img/front/youtube.svg" id="svg-img2">youtube</div>
		<div class="swiper-slide" id="swi-img3"><img src="/img/front/microphone.svg" id="svg-img3">cast</div>
	</div>
</div>

default

when onclick the div swiper-slide

when onclick other div swiper-slide

1 个答案:

答案 0 :(得分:0)

尝试这样。

$('.swiper-slide').on('click', function(){
  $('.swiper-slide').removeClass('selected');
  $(this).addClass('selected');
  if($('#swi-img1').hasClass("selected")){
    $('#svg-img1').attr('src','/img/front/photos-white.svg');
  }else{
    $('#svg-img1').attr('src','/img/front/photos.svg');
  }
  
  if($('#swi-img2').hasClass("selected")){
    $('#svg-img2').attr('src','/img/front/youtube-white.svg');
  } else {
    $('#svg-img2').attr('src','/img/front/youtube.svg');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="swiper-container pt-2 pb-4" id="contents-swiper">
	<div class="swiper-wrapper">
		<div class="swiper-slide" id="swi-img1"><img src="/img/front/photos.svg" id="svg-img1">card</div>
    
		<div class="swiper-slide" id="swi-img2"><img src="/img/front/youtube.svg" id="svg-img2">youtube</div>
    
		<div class="swiper-slide" id="swi-img3"><img src="/img/front/microphone.svg" id="svg-img3">cast</div>
	</div>
</div>