2017-05-20 2 views
0

私はJavaScriptに慣れていません。ウェブページを構築しようとしています。サイドバーにその製品の3つのイメージがあり、中間に1つのメインイメージがあります。ユーザーがそのサイドバーイメージをクリックします。私はこれについてどうやって行くのか分かりません。私はすでにオンラインで見つかった方法をいくつか試しましたが、そのうちの1つは です。How to swap image and video to another div?サイドバーの画像をクリックすると、サイドバーから中間のdivに画像をスワップするにはどうすればいいですか?

しかし、これらは私にとってはうまくいきません。 This is the screenshot of my webpage

+0

作業しているページの関連するHTML、CSS、およびJavaScriptを提供してください。 –

答えて

1

あなたがしなければならないことは、両方のイメージを変数に保存してからスワップすることです。あなたはこの問題を解決するために(自分のサイドバーの画像のそれぞれに)取り扱いのjavascriptのイベントを使用することができます

var imgleft, 
 
    imgcenter, 
 
    $center = $(".center img"); 
 
$(".sidebar img").click(function(){ 
 
    imgleft = $(this).attr("src"); 
 
    imgcenter = $center.attr("src"); 
 
    $center.attr("src", imgleft); 
 
    $(this).attr("src", imgcenter); 
 
});
.sidebar{ 
 
    position: absolute; 
 
    top: 0; 
 
    width: 70px; 
 
    height: 100%; 
 
    background: red; 
 
} 
 
.center{ 
 
    width: 80px; 
 
    height: 80px; 
 
    margin:25% auto; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="sidebar"> 
 
    <img src="http://placehold.it/70x70"> 
 
    <img src="http://placehold.it/70x60"> 
 
    <img src="http://placehold.it/70x50"> 
 
</div> 
 
<div class="center"> 
 
    <img src="http://placehold.it/70x40"> 
 
</div>

1

以下の例を見てください。まず、あなたのhtmlに次のJavaスクリプトコードを追加します。

<script type="text/javascript"> 
    function changeToImage1(){ 
     if(centerImage.src != "[1st-image-url.*]"){ 
      centerImage.src = "[1st-image-url.*]"; 
     } 
    } 
    function changeToImage2(){ 
     if(centerImage.src != "[2nd-image-url.*]"){ 
      centerImage.src = "[2nd-image-url.*]"; 
     } 
    } 
    function changeToImage3(){ 
     if(centerImage.src != "[3rd-image-url.*]"){ 
      centerImage.src = "[3rd-image-url.*]"; 
     } 
    } 
</script> 

次に、あなたは単にあなたの3サイドバーのdivのに応じてののonClick属性に上記の機能を追加することができます。これは次のようにすることができます:

<div id = "first" onclick = "changeToImage1()"> 
    ... 
</div> 
<div id = "second" onclick = "changeToImage2()"> 
    ... 
</div> 
<div id = "third" onclick = "changeToImage3()"> 
    ... 
</div> 
関連する問題