如何使用javascript展开和折叠<div>?</div>

时间:2013-07-04 00:18:48

标签: javascript jquery

我在自己的网站上创建了一个列表。此列表由foreach循环创建,该循环使用来自我的数据库的信息构建。每个项目都是一个具有不同部分的容器,因此这不是像1,2,3等等的列表。我列出了包含信息的重复部分。在每个部分中,都有一个小节。一般构建如下:

<div>
    <fieldset class="majorpoints" onclick="majorpointsexpand($(this).find('legend').innerHTML)">
    <legend class="majorpointslegend">Expand</legend>
    <div style="display:none" >
        <ul>
            <li></li>
            <li></li>
        </ul>
    </div>
</div>

所以,我试图用onclick =“majorpointsexpand($(this).find('legend')。innerHTML)调用一个函数”

我试图操作的div是默认情况下的style =“display:none”,我想使用javascript使其在点击时可见。

“$(this).find('legend')。innerHTML”试图在函数中传递“Expand”作为参数。

这是javascript:

function majorpointsexpand(expand)
    {
        if (expand == "Expand")
            {
                document.write.$(this).find('div').style = "display:inherit";
                document.write.$(this).find('legend').innerHTML = "Collapse";
            }
        else
            {
                document.write.$(this).find('div').style = "display:none";
                document.write.$(this).find('legend').innerHTML = "Expand";
            }
    }

我几乎100%确定我的问题是语法,而且我对javascript的工作原理并不十分了解。

我确实将jQuery链接到文档:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

<head></head>部分。

12 个答案:

答案 0 :(得分:166)

好的,所以你有两个选择:

  1. 使用jQuery UI的手风琴 - 它美观,简单,快捷。查看更多信息here
  2. 或者,如果你还想自己做这件事,你可以删除fieldset(无论如何都不能在语义上使用它)并自己创建一个结构。
  3. 这是你如何做到的。创建一个这样的HTML结构:

    <div class="container">
        <div class="header"><span>Expand</span>
    
        </div>
        <div class="content">
            <ul>
                <li>This is just some random content.</li>
                <li>This is just some random content.</li>
                <li>This is just some random content.</li>
                <li>This is just some random content.</li>
            </ul>
        </div>
    </div>
    

    使用此CSS :(这是为了在页面加载时隐藏.content内容。

    .container .content {
        display: none;
        padding : 5px;
    }
    

    然后,使用jQuery,为标题写一个click事件。

    $(".header").click(function () {
    
        $header = $(this);
        //getting the next element
        $content = $header.next();
        //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
        $content.slideToggle(500, function () {
            //execute this after slideToggle is done
            //change text of header based on visibility of content div
            $header.text(function () {
                //change text based on condition
                return $content.is(":visible") ? "Collapse" : "Expand";
            });
        });
    
    });
    

    以下是演示:http://jsfiddle.net/hungerpain/eK8X5/7/

答案 1 :(得分:19)

怎么样:

jQuery的:

$('.majorpoints').click(function(){
    $(this).find('.hider').toggle();
});

HTML

<div>
  <fieldset class="majorpoints">
    <legend class="majorpointslegend">Expand</legend>
    <div class="hider" style="display:none" >
        <ul>
            <li>cccc</li>
            <li></li>
        </ul>
    </div>
</div>

Fiddle

这样您就可以将click事件绑定到.majorpoints类,而不必每次都在HTML中编写它。

答案 2 :(得分:6)

这里有很多问题

我已经设置了一个适合你的小提琴:http://jsfiddle.net/w9kSU/

$('.majorpointslegend').click(function(){
    if($(this).text()=='Expand'){
        $('#mylist').show();
        $(this).text('Colapse');
    }else{
        $('#mylist').hide();
        $(this).text('Expand');
    }
});

答案 3 :(得分:6)

所以,首先,你的Javascript甚至不使用jQuery。有几种方法可以做到这一点。例如:

首先,使用jQuery toggle方法:

<div class="expandContent">
        <a href="#">Click Here to Display More Content</a>
 </div>
<div class="showMe" style="display:none">
        This content was hidden, but now shows up
</div>

<script>  
    $('.expandContent').click(function(){
        $('.showMe').toggle();
    });
</script>

jsFiddle:http://jsfiddle.net/pM3DF/

另一种方法是使用jQuery show方法:

<div class="expandContent">
        <a href="#">Click Here to Display More Content</a>
 </div>
<div class="showMe" style="display:none">
        This content was hidden, but now shows up
</div>

<script>
    $('.expandContent').click(function(){
        $('.showMe').show();
    });
</script>

jsFiddle:http://jsfiddle.net/Q2wfM/

然而第三种方法是使用jQuery的slideToggle方法,它允许一些效果。比如$('#showMe').slideToggle('slow');会慢慢显示隐藏的div。

答案 4 :(得分:5)

您可能想看一下这个简单的Javascript方法,当点击链接以进行面板/ div扩展或折叠时,可以调用它。

<script language="javascript"> 
function toggle(elementId) {
    var ele = document.getElementById(elementId);
    if(ele.style.display == "block") {
            ele.style.display = "none";
    }
    else {
        ele.style.display = "block";
    }
} 
</script>

您可以传递div ID,它将在显示'none'或'block'之间切换。

snip2code - How to collapse a div in html

的原始来源

答案 5 :(得分:3)

查看toggle() jQuery 功能:

http://api.jquery.com/toggle/

此外,innerHTML jQuery 功能为.html()

答案 6 :(得分:3)

尝试jquery,

  <div>
        <a href="#" class="majorpoints" onclick="majorpointsexpand(" + $('.majorpointslegend').html() + ")"/>
        <legend class="majorpointslegend">Expand</legend>
        <div id="data" style="display:none" >
            <ul>
                <li></li>
                <li></li>
            </ul>
        </div>
    </div>


function majorpointsexpand(expand)
    {
        if (expand == "Expand")
            {
                $('#data').css("display","inherit");
                $(".majorpointslegend").html("Collapse");
            }
        else
            {
                $('#data').css("display","none");
                $(".majorpointslegend").html("Expand");
            }
    }

答案 7 :(得分:3)

Here there is my example of animation a staff list with expand a description.

<html>
  <head>
    <style>
      .staff {            margin:10px 0;}
      .staff-block{       float: left; width:48%; padding-left: 10px; padding-bottom: 10px;}
      .staff-title{       font-family: Verdana, Tahoma, Arial, Serif; background-color: #1162c5; color: white; padding:4px; border: solid 1px #2e3d7a; border-top-left-radius:3px; border-top-right-radius: 6px; font-weight: bold;}
      .staff-name {       font-family: Myriad Web Pro; font-size: 11pt; line-height:30px; padding: 0 10px;}
      .staff-name:hover { background-color: silver !important; cursor: pointer;}
      .staff-section {    display:inline-block; padding-left: 10px;}
      .staff-desc {       font-family: Myriad Web Pro; height: 0px; padding: 3px; overflow:hidden; background-color:#def; display: block; border: solid 1px silver;}
      .staff-desc p {     text-align: justify; margin-top: 5px;}
      .staff-desc img {   margin: 5px 10px 5px 5px; float:left; height: 185px; }
    </style>
  </head>
<body>
<!-- START STAFF SECTION -->
<div class="staff">
  <div class="staff-block">
    <div  class="staff-title">Staff</div>
    <div class="staff-section">
        <div class="staff-name">Maria Beavis</div>
        <div class="staff-desc">
          <p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Maria earned a Bachelor of Commerce degree from McGill University in 2006 with concentrations in Finance and International Business. She has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007.</p>
        </div>
        <div class="staff-name">Diana Smitt</div>
        <div class="staff-desc">
          <p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Diana joined the Diana Smitt Group to help contribute to its ongoing commitment to provide superior investement advice and exceptional service. She has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses.</p>
        </div>
        <div class="staff-name">Mike Ford</div>
        <div class="staff-desc">
          <p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Mike: A graduate of École des hautes études commerciales (HEC Montreal), Guillaume holds the Chartered Investment Management designation (CIM). After having been active in the financial services industry for 4 years at a leading competitor he joined the Mike Ford Group.</p>
        </div>
    </div>
  </div>

  <div class="staff-block">
    <div  class="staff-title">Technical Advisors</div>
    <div class="staff-section">
        <div class="staff-name">TA Elvira Bett</div>
        <div class="staff-desc">
          <p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Elvira has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007. Laura works directly with Caroline Hild, aiding in revising client portfolios, maintaining investment objectives, and executing client trades.</p>
        </div>
        <div class="staff-name">TA Sonya Rosman</div>
        <div class="staff-desc">
          <p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Sonya has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses through the Canadian Securities Institute. She recently completed her Wealth Management Essentials course and became an Investment Associate.</p>
        </div>
        <div class="staff-name">TA Tim Herson</div>
        <div class="staff-desc">
          <p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Tim joined his father&#8217;s group in order to continue advising affluent families in Quebec. He is currently President of the Mike Ford Professionals Association and a member of various other organisations.</p>
        </div>
    </div>
  </div>
</div>
<!-- STOP STAFF SECTION -->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

<script language="javascript"><!--
//<![CDATA[
$('.staff-name').hover(function() {
    $(this).toggleClass('hover');
});
var lastItem;
    $('.staff-name').click(function(currentItem) {
        var currentItem = $(this);
      if ($(this).next().height() == 0) {
          $(lastItem).css({'font-weight':'normal'});
          $(lastItem).next().animate({height: '0px'},400,'swing');
          $(this).css({'font-weight':'bold'});
          $(this).next().animate({height: '300px',opacity: 1},400,'swing');
      } else {
          $(this).css({'font-weight':'normal'});
          $(this).next().animate({height: '0px',opacity: 1},400,'swing');
      }
      lastItem = $(this);
    });
//]]>
--></script>

</body></html>

<强> Fiddle

答案 8 :(得分:2)

由于您在页面上有jQuery,因此可以删除onclick属性和majorpointsexpand函数。将以下脚本添加到页面底部,或者最好添加到外部.js文件:

$(function(){

  $('.majorpointslegend').click(function(){
    $(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
  });

});

此解决方案应该与您的HTML一起使用,但它不是一个非常强大的答案。如果您更改fieldset布局,则可能会破坏它。我建议您在隐藏的div中添加class属性,例如class="majorpointsdetail",然后使用此代码:

$(function(){

  $('.majorpoints').on('click', '.majorpointslegend', function(event){
    $(event.currentTarget).find('.majorpointsdetail').toggle();
    $(this).text( $(this).is(':visible')?'Collapse':'Expand' );
  });

});

Obs:您的问题中没有关闭</fieldset>标记,所以我假设隐藏的div位于字段集内。

答案 9 :(得分:1)

如果您使用数据角色可折叠,例如

    <div id="selector" data-role="collapsible" data-collapsed="true">
    html......
    </div>

然后它将关闭扩展的div

    $("#selector").collapsible().collapsible("collapse");   

答案 10 :(得分:1)

查看Jed Foster的Readmore.js库。

它的用法很简单:

$(document).ready(function() {
  $('article').readmore({collapsedHeight: 100});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://fastcdn.org/Readmore.js/2.1.0/readmore.min.js" type="text/javascript"></script>

<article>
  <p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>

  <p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>

  <p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance, waged war to bring everyone under their rule; a few idiots tried to fight it, among them myself. I'm Malcolm Reynolds, captain of Serenity. Got a good crew: fighters, pilot, mechanic. We even picked up a preacher, and a bona fide companion. There's a doctor, too, took his genius sister out of some Alliance camp, so they're keeping a low profile. You got a job, we can do it, don't much care what it is.</p>

  <p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>

以下是配置窗口小部件的可用选项:

{
  speed: 100,
  collapsedHeight: 200,
  heightMargin: 16,
  moreLink: '<a href="#">Read More</a>',
  lessLink: '<a href="#">Close</a>',
  embedCSS: true,
  blockCSS: 'display: block; width: 100%;',
  startOpen: false,

  // callbacks
  blockProcessed: function() {},
  beforeToggle: function() {},
  afterToggle: function() {}
},

使用可以像使用它一样

$('article').readmore({
  collapsedHeight: 100,
  moreLink: '<a href="#" class="you-can-also-add-classes-here">Continue reading...</a>',
});

希望对您有帮助。

答案 11 :(得分:0)

使用纯 JavaScript

const collapsableBtn = document.querySelectorAll('.collapsable-toggle');

for (let index = 0; index < collapsableBtn.length; index++) {
    collapsableBtn[index].addEventListener('click', function(e) {
        // e.preventDefault();
        e.stopImmediatePropagation();

        iterateElement = this;

        getCollapsableParent = iterateElement.parentElement;

        if(getCollapsableParent.classList.contains('show')) {
            getCollapsableParent.classList.remove('show')
            iterateElement.innerText = iterateElement.getAttribute('data-onCloseText');

        } else {
            getCollapsableParent.classList.add('show');
            iterateElement.innerText = iterateElement.getAttribute('data-onOpenText');
        }
    })
}
.collapsable-container #expand {
   display:none;
}
.collapsable-container.show #expand {
    display:block;
}
<div class="collapsable-container">
    <a href="javascript:void(0);" class="collapsable-toggle" data-onOpenText="Hide First Content" data-onCloseText="Show First Content">Show First Content</a>
    <div id="expand">
        This is some Content
    </div>
 </div>
 
 
 <div class="collapsable-container">
    <a href="javascript:void(0);" class="collapsable-toggle" data-onOpenText="Hide Second Content" data-onCloseText="Show Second Content">Show Second Content</a>
    <div id="expand">
        This is some Content
    </div>
 </div>