簡體   English   中英

想打開另一個div時關閉一個div

[英]Would like to close a div when open another div

我已經能夠讓我的div打開並改變圖像,但我想要發生的是當我打開一個,另一個關閉,我不知道該怎么做。

我有這樣的多個div 新聞的每個id都是它自己的個人名稱:

<div class="article" id="news">
    <h2>Hot News: Board Votes to Improve Highways</h2>
    <p>As Sporktown’s native and tourist population has increased, so has traffic. The good news is we are taking steps to deal with it. Before traffic becomes too much of a problem we have a plan to expand current highways and improve current ones.</p>
    <div class="moreText">
        <p>
            As part of the new plan, Route 7 will be expanded from a two-way highway to a four-lane highway. This will dramatically speed up North–South travel through that corridor.
        </p>
        <p>
            In addition to the road widening on Route 7, we have finally received approval to for the extension. The original plan called for Route to continue farther North. The project is finally cleared and work has already begun.
        </p>
    </div>
    <img src="img/more-button.png" width="51" height="16" class="changeTextButton">    
</div>

這是我到目前為止的jquery腳本:

$(document).ready(function() 
{
    $('.changeTextButton').click( function() 
    {
        $(this).siblings('.moreText').slideToggle(500);
        if ( $(this).attr('src') == 'img/more-button.png') 
        {
            $(this).attr('src', 'img/less-button.png');
        }
        else 
        {
            $(this).attr('src', 'img/more-button.png'); 
        }
    });
});

你可以使用類.articles關閉所有其他div,然后使用div的相應id來顯示

$(".articles").hide();
$("#news").show();

這將隱藏所有具有類清晰度的div並顯示div具有id作為新聞

只需添加

$('.moreText').slideUp();

這一行之后:

$('.changeTextButton').click( function() {

這將向上滑動“.moreText”的所有實例,但當前打開的實例除外。

試試這個腳本

$(document).ready(function() {
var $parentid = "";

    $('.changeTextButton').click( function() {

          if($parentid!="" && $parentid!=$(this).parent().attr("id")){
               $("#"+$parentid).find(".moreText").slideUp();
          }

        $(this).siblings('.moreText').slideToggle(500);
        $parentid=$(this).parent().attr("id");

        if ( $(this).attr('src') == 'img/more-button.png') {
            $(this).attr('src', 'img/less-button.png');
        }
        else {
            $(this).attr('src', 'img/more-button.png'); 
        }

    });

});

獲取全局變量,每個changeTextButton上的div的賦值對象/ id單擊此變量並獲取prevoius id的id並隱藏它

聲明全局變量:

window.news;//news is global variable

隱藏/顯示div

$("#"+news).hide();
$("#newdiv").show();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM