ฉันจะขยายและยุบ <div> โดยใช้ javascript ได้อย่างไร


96

ฉันได้สร้างรายการบนไซต์ของฉันแล้ว รายการนี้สร้างขึ้นโดย foreach loop ที่สร้างด้วยข้อมูลจากฐานข้อมูลของฉัน แต่ละรายการเป็นคอนเทนเนอร์ที่มีส่วนต่างกันดังนั้นนี่จึงไม่ใช่รายการเช่น 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" กำลังพยายามส่งผ่านในกรณีนี้ "ขยาย" เป็นอาร์กิวเมนต์ในฟังก์ชัน

นี่คือจาวาสคริปต์:

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% แน่ใจว่าปัญหาของฉันคือไวยากรณ์และฉันไม่เข้าใจวิธีการทำงานของจาวาสคริปต์มากนัก

ฉันมี jQuery ที่เชื่อมโยงกับเอกสารด้วย:

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

ใน<head></head>ส่วน.


2
ฉันคิดว่าสิ่งที่คุณพยายามจะบรรลุคือหีบเพลงjqueryui.com/accordion
Marc

1
$ นี่คือฉันพยายามพูดว่า "สัมพันธ์กับ" องค์ประกอบ HTML ที่ฟังก์ชันถูกเรียกใช้ภายใน
Ryan Mortensen

1
@hungerpain - ฉันคิดว่าผู้ถามอาจจะใหม่สำหรับ jQuery $(this)และเพียงแค่ลืมวงเล็บรอบ หวังว่านี่จะช่วยได้
jmort253

2
ฉันคิดว่าคุณควรศึกษาเพิ่มเติมเกี่ยวกับ jQuery ก่อน เห็นได้ชัดว่าคุณไม่รู้มากเกี่ยวกับความแตกต่างระหว่าง jQuery และ JavaScript
tom10271

1
@aokaddaoc คุณพูดถูกจริงๆ;)
Ryan Mortensen

คำตอบ:


184

เอาล่ะคุณมีสองตัวเลือกที่นี่:

  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 เพื่อขยายเทียบกับส่วนหัวที่ฉันคลิกซึ่งมีความสำคัญเนื่องจากฉันอาจมีรายการในรายการที่แตกต่างกันหลายรายการขึ้นอยู่กับการตั้งค่าของผู้ใช้และปัจจัยอื่น ๆ
Ryan Mortensen

1
@Unipartisandev ดูสิ่งนี้: jsfiddle.net/hungerpain/476Nqตัวอย่างเต็มรูปแบบ :)
krishwader

ฉันขอขอบคุณสำหรับความช่วยเหลือ จะมีส่วนอื่น ๆ ของไซต์ที่ไม่ต้องสงสัยเลยว่าจำเป็นต้องใช้หีบเพลงถึงแม้ว่าสิ่งนี้จะเป็นตัวอย่างที่แสดงทั้งหมดหรือไม่มีเลยก็ตาม ฉันยังคงมีปัญหา jQuery ของฉันล้าสมัยและไม่โหลด ได้รับการแก้ไขแล้ว แต่ฉันยังไม่ได้ผล ฉันยุ่งกับมันมาเป็นชั่วโมงแล้วฉันจะนอนกับมัน บางทีพรุ่งนี้มันจะโดนฉัน
Ryan Mortensen

ยอดเยี่ยมขอบคุณ ประหยัดเวลาได้มาก!
Basil Musa

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>

ซอ

ด้วยวิธีนี้คุณจะเชื่อมโยงเหตุการณ์การคลิกกับ.majorpointsชั้นเรียนโดยที่คุณไม่ต้องเขียนลงใน HTML ทุกครั้ง


สวัสดี raam86 ฉันจะก้าวไปอีกขั้นและทำ. ค้นหา div โดยใช้คลาสแทน id หากผู้ถามมีชุดฟิลด์เหล่านี้หลายชุดในหน้าเว็บเขาจะต้องการกำหนดเป้าหมายตัวซ่อนสำหรับชุดที่เกี่ยวข้องกับชุดฟิลด์เฉพาะที่คลิก หวังว่านี่จะช่วยได้! :) ตัวอย่างเช่นคุณสามารถใช้. closest เพื่อรับการอ้างอิงถึง div พาเรนต์จากนั้นใช้. find เพื่อค้นหา div ด้วย class = "hider" แทน
jmort253

1
ฉันรู้ว่ามันเป็นเวลาตีสาม;) แต่ฉันเพิ่งสังเกตว่าคุณยังใช้ id ใน jsFiddle ของคุณ ซึ่งอาจส่งผลให้เกิดพฤติกรรมที่ไม่ได้กำหนดเนื่องจากข้อกำหนดของ W3C ระบุว่าแต่ละ id ควรไม่ซ้ำกัน หากคุณเปลี่ยน hider เป็นคลาสสิ่งนี้จะมีภูมิคุ้มกันมากกว่าสำหรับจุดบกพร่องหรือพฤติกรรมที่ไม่สามารถอธิบายได้ในเบราว์เซอร์อื่น หวังว่านี่จะช่วยได้!
jmort253

ที่จริงควรเป็น $ ('. majorpointslegend') คลิก (function () {$ (this) .parent (). find ('. hider'). toggle ();}); หรือเมื่อคลิกที่ใด ๆ ในชุดฟิลด์ก็จะยุบลง
Awatatah

7

ก่อนอื่น Javascript ของคุณไม่ได้ใช้ jQuery ด้วยซ้ำ มีสองวิธีในการดำเนินการนี้ ตัวอย่างเช่น:

วิธีแรกโดยใช้toggleวิธีjQuery :

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

อีกวิธีหนึ่งคือใช้showวิธีjQuery :

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

วิธีที่สามคือการใช้slideToggleวิธีของ jQuery ซึ่งอนุญาตให้ใช้เอฟเฟกต์บางอย่าง เช่น$('#showMe').slideToggle('slow');ที่ช้าจะแสดง div ที่ซ่อนอยู่


สมมติว่าเขามีองค์ประกอบ showMe มากกว่าหนึ่งรายการในหน้านี้ โปรดจำไว้ว่าเขาใช้ for loop เพื่อสร้างรายการเหล่านี้ดังนั้นการกำหนดเป้าหมาย class = "showMe" จะส่งผลต่ออินสแตนซ์แรกขององค์ประกอบนั้นเท่านั้น ข้อเสนอแนะของฉันคือการอ้างอิงองค์ประกอบ showMe ที่เกี่ยวข้องกับหนึ่งคลิก แล้วนี่จะเป็นทางออกที่ดี หวังว่านี่จะช่วยได้! :)
jmort253

ถูกต้อง แต่เขาใช้ลูปเพื่อสร้างรายการในชุดของ<li>องค์ประกอบไม่ใช่ div ไม่ว่าจะด้วยวิธีใดเขาก็สามารถใช้รหัสองค์ประกอบนั้นเพื่อซ่อนได้
Michael Hawkins

คุณกำลังคิดถึงส่วนย่อยและลืมไปว่าจะมีมากกว่านี้ แต่ละส่วนเป็นประชากรที่มีองค์ประกอบ li ในหมวด "รายการนี้สร้างขึ้นโดย foreach loop ที่สร้างด้วยข้อมูลจากฐานข้อมูลของฉันแต่ละรายการเป็นคอนเทนเนอร์ที่มีส่วนต่างกันดังนั้นนี่จึงไม่ใช่รายการเช่น 1, 2, 3 ... ฯลฯ ฉันกำลังแสดงรายการส่วนที่ซ้ำพร้อมข้อมูล . ในแต่ละส่วนจะมีส่วนย่อย " ในระยะสั้นเขาเพียงแค่แสดงให้คุณเห็นเพียงส่วนเดียวแม้ว่าจะมีมากกว่านั้นก็ตาม
jmort253

6

คุณอาจต้องการดูวิธีการ 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 และมันจะสลับระหว่างการแสดง 'ไม่มี' หรือ 'บล็อก'

แหล่งที่มาดั้งเดิมบนsnip2code - วิธีการยุบ div ใน html


6

ปัญหามากมายที่นี่

ฉันได้ตั้งค่าซอที่เหมาะกับคุณแล้ว: http://jsfiddle.net/w9kSU/

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

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.html()ฟังก์ชั่น


1
สวัสดียินดีต้อนรับสู่ Stack Overflow! คุณควรแสดงตัวอย่างเพื่อให้คำตอบของคุณสมบูรณ์ยิ่งขึ้น หากลิงก์ถูกทำลายคำตอบของคุณจะยังมีประโยชน์ต่อผู้เยี่ยมชมในอนาคต โชคดี! :)
jmort253

คุณสามารถแก้ไขเพื่อเพิ่มตัวอย่างหรือเพิ่มเป็นความคิดเห็น ขอบคุณ.
JGallardo

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

});

ข้อสังเกต: ไม่มี</fieldset>แท็กปิดในคำถามของคุณดังนั้นฉันจึงถือว่า div ที่ซ่อนอยู่ในชุดฟิลด์


คุณถูกต้อง มีชุดฟิลด์ปิด แต่ฉันพลาดในคำถามของฉัน มันมาทันทีหลังจากปิดด้านใน </div> และก่อนปิดด้านนอก </div>
Ryan Mortensen

1

หากคุณใช้ data-role ที่สามารถพับได้เช่น

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

จากนั้นมันจะปิด div ที่ขยายแล้ว

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

1

ลองดูห้องสมุดReadmore.jsของ Jed Foster

การใช้งานทำได้ง่ายเพียง:

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

ฉันหวังว่ามันจะช่วยได้

โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.