자바 스크립트를 사용하여 <div>를 확장 및 축소하려면 어떻게해야합니까?


96

내 사이트에 목록을 만들었습니다. 이 목록은 내 데이터베이스의 정보로 빌드되는 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"를 전달하려고합니다.

다음은 자바 스크립트입니다.

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 2013

1
@hungerpain-나는 질문자가 jQuery를 처음 접했을 수 있고 괄호를 잊었다 고 생각합니다 $(this). 도움이 되었기를 바랍니다.
jmort253 2013-07-04

2
먼저 jQuery에 대해 더 공부해야한다고 생각합니다. 분명히 당신은 jQuery와 JavaScript의 차이점에 대해 많이 알지 못합니다
tom10271

1
@aokaddaoc 당신이 절대적으로 옳았다)
라이언 모텐슨

답변:


183

여기에 두 가지 옵션이 있습니다.

  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
fieldset은 필수가 아닙니다. 나는 그것을 제거하고 그냥 테두리를 사용합니다. 이것은 내가 클릭 한 헤더를 기준으로 확장 할 div를 선택하기 때문에 탁월합니다. 사용자 설정 및 기타 요인에 따라 여러 항목이 나열 될 수 있기 때문에 중요합니다.
Ryan Mortensen

1
이에 @Unipartisandev보기 jsfiddle.net/hungerpain/476Nq : 전체 깃털 예
krishwader

도움을 주셔서 정말 감사합니다. 아코디언을 사용할 필요가있는 사이트의 다른 부분이있을 것입니다. 비록이 특정 항목이 전부 또는 전혀 표시되지 않는 예 일지라도 말입니다. 여전히 문제가 있습니다. 내 jQuery가 오래되어로드되지 않았습니다. 수정되었지만 여전히 작동하지 않습니다. 나는 지금 좋은 시간 동안 그것을 엉망으로 만들었습니다. 아마 내일 나를 때릴 것입니다.
Ryan Mortensen

훌륭합니다, 감사합니다. 많은 시간을 절약했습니다!
Basil Musa 2014

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, 나는 이것을 한 걸음 더 나아가 id 대신 클래스를 사용하여 div에서 .find를 수행 할 것입니다. 질문자가 페이지에 이러한 필드 세트가 여러 개있는 경우 클릭 한 특정 필드 세트와 관련된 항목에 대해 hider를 대상으로 지정할 수 있습니다. 도움이 되었기를 바랍니다! :) 예를 들어 .closest를 사용하여 부모 div에 대한 참조를 가져온 다음 .find를 사용하여 대신 class = "hider"가있는 div를 찾을 수 있습니다.
jmort253

1
오전 3 시라는 것을 알고 있지만 jsFiddle에서 여전히 ID를 사용하고 있음을 알았습니다. W3C 사양에 각 ID가 고유해야한다고 명시되어 있으므로 정의되지 않은 동작이 발생할 수 있습니다. hider를 클래스로 변경하면 버그 나 다른 브라우저의 이상하고 설명 할 수없는 동작에 더 영향을받지 않습니다. 도움이 되었기를 바랍니다!
jmort253 2013-07-04

실제로 $ ( '. majorpointslegend'). click (function () {$ (this) .parent (). find ( '. hider'). toggle ();}); 그렇지 않으면 fieldset의 아무 곳이나 클릭하면 축소됩니다.
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/

그러나 세 번째 방법은 slideToggle일부 효과를 허용하는 jQuery 메서드 를 사용하는 것입니다. 예를 들어 $('#showMe').slideToggle('slow');숨겨진 div가 천천히 표시됩니다.


페이지에 이러한 showMe 요소 중 하나 이상이 있다고 가정 해 보겠습니다. 그는 for 루프를 사용하여 목록을 작성하고 있으므로 class = "showMe"를 타겟팅하면 해당 요소의 첫 번째 인스턴스에만 영향을 미칩니다. 내 제안은 클릭 한 요소와 관련하여 showMe 요소를 참조하는 것입니다. 그렇다면 이것은 좋은 해결책이 될 것입니다. 도움이 되었기를 바랍니다! :)
jmort253 2013-07-04

맞습니다.하지만 그는 루프를 사용하여 <li>div가 아닌 일련의 요소로 목록을 작성하고 있습니다. 어느 쪽이든 그는 요소 ID를 사용하여 숨길 수 있습니다.
Michael Hawkins

당신은 하위 섹션을 생각하고 있으며 이것들이 더 많이있을 것이라는 사실을 잊고 있습니다. 각 섹션하위 섹션의 li 요소로 채워집니다 . "이 목록은 내 데이터베이스의 정보로 빌드되는 foreach 루프에 의해 생성됩니다. 각 항목은 서로 다른 섹션이있는 컨테이너이므로 1, 2, 3 ... 등과 같은 목록이 아닙니다. 정보가있는 반복 섹션을 나열하고 있습니다. . 각 섹션에는 하위 섹션이 있습니다. " 요컨대, 그는 더 많은 것이있을지라도 단지 하나의 섹션 만 보여주었습니다.
jmort253

6

패널 / 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로 사업부를 축소하기


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 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가 fieldset 안에 있다고 가정합니다.


당신이 맞습니다. 마감 필드 셋이 있지만 제 질문에서 놓쳤습니다. 그것은 바로 뒤에 오는 닫는 내부 </ DIV>와 닫는 외부 전에 </ DIV>
라이언 모텐슨

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

도움이되기를 바랍니다.

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.