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


95

我已经在我的网站上创建了一个列表。该列表由一个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>节中。


2
我想您正在尝试实现的是手风琴jqueryui.com/accordion
Marc

1
$ this是我要说的是“相对于”触发函数内部的HTML元素。
Ryan Mortensen

1
@hungerpain-我认为asker可能不是jQuery的新手,只是忘记了括号$(this)。希望这可以帮助。
jmort253

2
我认为您应该首先学习有关jQuery的更多信息。显然,您对jQuery和JavaScript之间的区别了解不多
tom10271 '16

1
@aokaddaoc,您说得很对;)
Ryan Mortensen

Answers:


181

好的,所以您在这里有两个选择:

  1. 使用jQuery UI的手风琴-美观,便捷,快速。在这里查看更多信息
  2. 或者,如果您仍然想自己执行此操作,则可以删除fieldset(无论如何在语义上都不适合为此目的使用)并自己创建一个结构。

这是您的操作方式。创建这样的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/


9
+1,因为如果页面上有多个DIV元素,这将解决问题。换句话说,由于您的目标是单击标题中的内容,因此可以很好地扩展。
jmort253

2
该字段集不是必须的。我将摆脱它,只使用边框。这非常好,因为它会选择div相对于我单击的标题进行扩展,这很重要,因为事实上,根据用户设置和其他因素,我可能会列出不同数量的所列项目。
瑞安·莫滕森

1
@Unipartisandev看看:jsfiddle.net/hungerpain/476Nq完整的示例:)
krishwader

我非常感谢您的帮助。毫无疑问,站点的其他部分将需要使用手风琴,即使这一件事只是显示全有或全无的示例。我仍然有问题。我的jQuery已过时且未加载。那是固定的,但我仍然无法正常工作。我已经把它弄乱了一个小时,我会睡在上面。也许明天会打我。
Ryan Mortensen

太好了,谢谢。节省大量时间!
罗勒·穆萨

21

怎么样:

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>

小提琴

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


嗨raam86,我将更进一步,并使用类而不是id在div上执行.find。如果请求者在页面上有多个这些字段集,那么他将要针对与单击的特定字段集相关的那个隐藏器。希望这可以帮助!:)例如,您可以使用.closest来获取对父div的引用,然后使用.find来查找带有class =“ hider”的div。
jmort253

1
我知道现在是凌晨3点;),但是我只是注意到您仍在jsFiddle中使用id。这可能会导致不确定的行为,因为W3C规范指出每个ID应该是唯一的。如果将Hider更改为类,则在其他浏览器中将更不会受到bug或奇怪,无法解释的行为的影响。希望这可以帮助!
jmort253

它实际上应该是$('。majorpointslegend')。click(function(){$(this).parent()。find('。hider')。toggle();}); 否则,当单击字段集中的任何位置时,它将折叠。
Awatatah

7

因此,首先,您的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/

第三种方法是使用slideTogglejQuery 的方法,该方法允许一些效果。如$('#showMe').slideToggle('slow');将缓慢显示隐藏的div。


假设他在页面上有多个showMe元素之一?记住,他使用for循环来构建这些列表,因此定位class =“ showMe”仅会影响该元素的第一个实例。我的建议是引用与单击有关的showMe元素。那么这将是一个很好的解决方案。希望这可以帮助!:)
jmort253

是的,但是他使用循环在一系列<li>元素(而不是div)中构建列表。无论哪种方式,他都可以使用元素ID然后将其隐藏。
Michael Hawkins

您正在考虑这些小节,而忘记了会有更多这些小节。每个部分被填充有在Li元素小节“此列表是由一个foreach循环创建的,该循环使用我数据库中的信息构建。每个项目都是一个包含不同部分的容器,因此,这不是像1,2,3 ...之类的列表。我正在列出重复的部分并包含信息在每个部分中都有一个小节。” 简而言之,即使您还会看到更多内容,他只是只向您展示了一个部分。
jmort253

6

这里有很多问题

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

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

5

您可能想看看单击链接以使panel / div展开或折叠时要调用的此简单Javascript方法。

<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,它将在显示“无”或“阻止”之间切换。

snip2code上的原始源代码 - 如何在HTML中折叠div


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");
            }
    }

3

这是我的动画工作人员列表示例,其中包含展开说明。

<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>

小提琴


3

看一下toggle() jQuery函数:

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

另外,innerHTML jQuery Function是.html()


1
您好,欢迎使用Stack Overflow!您应该显示一个示例,以便您的回答更加完整。如果链接断开,您的答案仍然对将来的访问者有用。祝好运!:)
jmort253

您可以编辑添加示例还是将其添加为注释?谢谢。
JGallardo 2015年

2

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

$(function(){

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

});

该解决方案应该可以与您的HTML一起使用,但实际上并不是一个非常可靠的答案。如果更改fieldset布局,则可能会破坏布局。我建议您class在该隐藏的div中放置一个属性,例如class="majorpointsdetail"并使用以下代码:

$(function(){

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

});

Obs:</fieldset>您的问题中没有结束标记,因此我假设隐藏的div位于字段集中。


没错 有一个封闭的字段集,但我在问题中错过了它。它紧接在内部</ div>之后和外部</ div>之前
Ryan Mortensen

1

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

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

然后它将关闭展开的div

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

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>',
});

希望对您有所帮助。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.