2017-04-07 12 views
0

ここまでは私がこれまで行ってきたことですが、今は正しく動作していません。何かご意見は?cssクラスをチェックして、アクティブな場合はイメージを変更したい場合src値

jQuery(document).ready(function($) { 
    if ($('#masthead').hasClass('is-fixed')) { 
    $('.site-logo-div').attr('src','second.jpg'); 
    } 
})(jQuery); 

編集: HTML

<header id="masthead" class="site-header header-fixed" role="banner" style="top: 32px;"> 

<div class="site-logo-div"><a href="https://danzerpress.com/" class="custom-logo-link"> 
<imgsrc="https://example.com" class="custom-logo" alt="" itemprop="logo" "></a> 
</div> 

WordpressのテーマJS

$(document).scroll(function(){ 
     var header_parent = header_fixed.parent(); 
     var p_to_top = header_parent.offset().top; 
     var st = $(document).scrollTop(); 
     if(st > p_to_top && st > 0) { 
      $wrap.addClass('is-fixed').removeClass('no-scroll'); 
      header_fixed.addClass('header-fixed'); 
      header_fixed.css('top', topbar+'px'); 
     } else { 
      header_fixed.removeClass('header-fixed'); 
      header_fixed.css('top', 'auto'); 
      $wrap.removeClass('is-fixed').addClass('no-scroll'); 
     } 
    }); 

} 

})。

+0

コンソールにエラーがありますか? HTML構造を投稿してください。 – Roy

+1

このコードは、ページをロードするときに初めて実行されるため、イベントを追加してクラスが存在するかどうかを確認する必要があります。そして、「アクティブ」のチェックはどこですか? –

+0

あなたが持っているものは正常に動作しますが、@ sajibが述べたように、ロード時にのみ動作します。クラスが追加されたときにこの動作が必要な場合は、そのクラスに影響を及ぼすイベントにフックする必要があります。 –

答えて

0
jQuery(document).ready(function($) { 
    if ($('#masthead').hasClass('is-fixed')) { 
    $('.site-logo-div a img').attr('src','second.jpg'); 
    } 
})(jQuery); 
+0

あなたのコードについて説明することを検討してください。 –

0

あなたはis-fixedクラスを追加または削除しながら、カスタムイベント(ここではclassChange)をトリガすることができます。その後、classChangeイベントコールバック関数内でイメージを変更します。

jQuery(document).ready(function($) { 
    var header_parent = header_fixed.parent(); 
    var p_to_top = header_parent.offset().top; 
    var st = $(document).scrollTop(); 
    if(st > p_to_top && st > 0) { 
     $wrap.addClass('is-fixed').removeClass('no-scroll'); 
     header_fixed.addClass('header-fixed'); 
     header_fixed.css('top', topbar+'px'); 
     $('#masthead').trigger('classChanged'); 
    } else { 
     header_fixed.removeClass('header-fixed'); 
     header_fixed.css('top', 'auto'); 
     $wrap.removeClass('is-fixed').addClass('no-scroll'); 
     $('#masthead').trigger('classChanged');  
    } 
    }); 

    $('#masthead').on('classChange', function() { 
    if ($('#masthead').hasClass('is-fixed')) { 
     $('.site-logo-div').attr('src','second.jpg'); 
    } else { 
     // do anything what you need when `is-fixed` class not exists 
    } 
    }); 
})(jQuery); 
0

prop機能を試してみてください!

jQuery(document).ready(function($) { 
    if ($('#masthead').prop('class')=="is-fixed") { 
    $('.site-logo-div').attr('src','second.jpg'); 
    } 
})(jQuery); 
関連する問題