使用JS切换显示/隐藏

时间:2016-03-28 02:45:29

标签: javascript jquery html css toggle

我对JS不熟悉,而且我无法让我的代码完全符合我的要求。 (参见JSFiddle https://jsfiddle.net/ey02227z/3/

我有3张图片,并希望能够点击图片并让它显示隐藏的div,然后当点击下一张图片时,我希望它隐藏第一个div并显示下一张图片。

(单击图像1查看HiddenContent1,单击Image2,它隐藏HiddenContent1并显示HiddenContent2等。)

这是我的代码:

(我没有包含任何JS,因为老实说,我不知道从哪里开始。)

提前谢谢!



Bundle bundle = this.getIntent().getExtras();

// Don't forget NullPointerException
if(bundle != null){
    final int IMPOSSIBLE_VALUE = -1; // default value
    boolean startNewGame = false;

    int gameNumberToResume = bundle.getInt("GameToResume", IMPOSSIBLE_VALUE);
    if(gameNumberToResume != IMPOSSIBLE_VALUE){
        startNewGame = true;
        // continue ..
    }    
}

#ImgContainer{
    text-align:center;
}

.Hidden{
    display:none;
}

.image:hover{
    border: 1px solid purple;
}

#HiddenContentContainer{
    text-align: center;
    min-height:50px;
    min-width:100%;
    border: 1px solid teal;
}




2 个答案:

答案 0 :(得分:1)

这可以解决您的问题。 试试吧

HTML

<div id="MainContainer">
<div id="ImgContainer">
    <a href="#"><img id="image1" class="image" data-target="#Hidden1" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+1';" onmouseout="this.src='http://placehold.it/150';" /></a>
    <a href="#"><img id="image2" class="image" data-target="#Hidden2" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+2';" onmouseout="this.src='http://placehold.it/150';" /></a>
    <a href="#"><img id="image3" class="image" data-target="#Hidden3" src="http://placehold.it/150" onmouseover="this.src='http://placehold.it/150?text=Image+3';" onmouseout="this.src='http://placehold.it/150';" /></a>
</div>
<div id="HiddenContentContainer">
    <h3>HIDDEN CONTENT SHOULD APPEAR HERE</h3>
    <div id="Hidden1" class="Hidden">This is My Hidden Content for Image 1</div>
    <div id="Hidden2" class="Hidden">This is My Hidden Content for Image 2</div>
    <div id="Hidden3" class="Hidden">This is My Hidden Content for Image 3</div>
</div>

JS:

//Normal hide-show
$(".image").click(function(){
$(".Hidden").hide();
    $($(this).attr("data-target")).show();
});

//For Toggle same code
$(".image").click(function(){
$(".Hidden").hide();
    if(!$($(this).attr("data-target")).hasClass("current")){
    $($(this).attr("data-target")).show().addClass("current");
  }
  else{
    $($(this).attr("data-target")).removeClass("current");
  }

});

答案 1 :(得分:0)

这是一个起点:

// listen to clicks from any of the links
$( '#ImgContainer a' ).on( 'click', function( e ) {
    e.preventDefault(); // not necessary in this case but good practice

    var link = $( this ); // the link that was clicked
    var index = link.index(); // its index position

    $( '#HiddenContentContainer div' ).addClass( 'Hidden' ); // reset all to hidden
    $( '#Hidden' + ( index + 1 ) ).removeClass( 'Hidden' ); // remove the hidden associated with this clicked link
});

包含的评论可帮助您更好地了解每行的内容。