programing

확장 및 축소 방법확장 및 축소 방법Javascript를 사용하시겠습니까?

kingscode 2023. 8. 29. 21:30
반응형

확장 및 축소 방법
Javascript를 사용하시겠습니까?

저는 제 사이트에 목록을 만들었습니다.이 목록은 내 데이터베이스의 정보로 작성되는 각 루프에 대해 작성됩니다.각 품목은 섹션이 다른 컨테이너이므로 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="주요 포인트 확장"(이것)으로 함수를 부르려고 합니다.을 찾아내다).내부 HTML)"

제가 조작하려는 div는 기본적으로 style="display:display"이며, 클릭 시 javascript를 사용하여 표시하고 싶습니다.

"$(이것).을 찾아내다).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>부분.

좋아요, 여기 두 가지 옵션이 있습니다.

  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를 사용하여 a를 작성합니다.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/

어때요?

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클래스 an 당신은 그것을 매번 HTML에 쓸 필요가 없습니다.

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

분할 ID를 전달하면 '없음' 또는 '차단' 표시가 전환됩니다.

snip2code의 원본 소스 - html에서 div를 축소하는 방법

먼저, 당신의 자바스크립트는 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');숨겨진 디브를 천천히 보여줄 겁니다

여기에 많은 문제가 있습니다.

제가 당신에게 맞는 바이올린을 준비했습니다: http://jsfiddle.net/w9kSU/

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

재쿼리를 시도해 보세요.

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

다음은 애니메이션에 대한 설명을 확장한 직원 목록의 예입니다.

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

피들

.toggle() jQuery 함수:

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

또한.innerHTML jQuery 함수는.html().

jQuery를 할 수 .onclick 및 속성majorpointsexpand합니다.다음 스크립트를 페이지 맨 아래 또는 가급적이면 외부 .js 파일에 추가합니다.

$(function(){

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

});

이 솔루션은 HTML과 그대로 작동해야 하지만 그다지 강력한 답변은 아닙니다.변경할 경우fieldset레이아웃이 깨질 수 있습니다.저는 당신이 그것을 제안합니다.classdiv의 , 를 들어 그숨겨디속성의브마, 치진치.class="majorpointsdetail"대신 이 코드를 사용합니다.

$(function(){

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

});

Obs: 마감이 없습니다.</fieldset>질문에 태그를 지정하면 숨겨진 디바가 필드 세트 안에 있다고 가정합니다.

예를 들어 데이터 역할 접기식을 사용한 경우.

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

그러면 확장된 디브를 닫을 것입니다.

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

한 번에 하나의 확장된 div만 허용하는 순수 javascript입니다.다중 레벨 하위 확장자를 허용합니다.HTML에는 확장자 내용만 필요합니다.javascript는 제목이 내용 데이터 속성과 svg 화살표를 구성하는 확장자 헤더를 만듭니다.

<style>
    /* expanders headers divs */
    .expanderHead {
        color: white;
        background-color: #1E9D8B;
        border: 2px solid #1E9D8B;
        margin-top: 9px;
        border-radius: 6px;
        padding: 3px;
        padding-left: 9px;
        cursor: default;
        font-family: Verdana;
        font-size: 14px;
    }

    .expanderHead:first-child {
        margin-top: 0 !important;
    }

    .expanderBody:last-child {
        margin-bottom: 0 !important;
    }

    /* expanders svg arrows */
    .expanderHead svg > g > path {
        fill: none;
        stroke: white;
        stroke-width: 2;
        stroke-miterlimit: 5;
        pointer-events: stroke;
    }

    /* expanders contents divs */
    .expanderBody {
        border: 2px solid #1E9D8B;
        border-top: 0;
        background-color: white;
        border-top-left-radius: 0;
        border-top-right-radius: 0;
        border-bottom-left-radius: 6px;
        border-bottom-right-radius: 6px;
        padding: 6px;
        font-family: Verdana;
        font-size: 12px;
    }

    /* widget window */
    .widget {
        width: 400px;
        background-color: white;
        padding: 9px;
        border: 2px solid #1E9D8B;
        border-top-left-radius: 6px;
        border-top-right-radius: 6px;
        border-bottom-left-radius: 6px;
        border-bottom-right-radius: 6px;
    }

</style>
<div class="widget">

    <div data-title="expander 1" class="expanderBody">
        expander 1 content
    </div>

    <div data-title="expander 2" class="expanderBody">
        expander 2 content
    </div>

    <div data-title="expander 3" class="expanderBody">

        <div>
            expander 3 content
        </div>

        <div data-title="expander 3.1" class="expanderBody">
            expander 3.1 content
        </div>

        <div data-title="expander 3.2" class="expanderBody">
            expander 3.2 content
        </div>

        <div data-title="expander 3.3" class="expanderBody">
            expander 3.3 content
        </div>

    </div>

</div>



<script>
    document.querySelectorAll(".expanderBody").forEach(item => {
        if (item.dataset.title) {
            // create expander header
            let divHeader = document.createElement("div");
            divHeader.className = "expanderHead";
            divHeader.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg>&nbsp;<span>" + item.dataset.title + "</span>";
            // expander click event
            divHeader.addEventListener("click", function () {
                // open / close expander
                for (let i = 0; i < this.parentNode.children.length; i++) {
                    let expander = this.parentNode.children[i];
                    // check if it's expander header
                    if (expander.className == "expanderHead") {
                        if (expander == this && expander.nextElementSibling.style.display == "none") {
                            // open expander body
                            expander.nextElementSibling.style.display = "";
                            expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 1 5 L 5 1'/><path d='M 5 1 L 10 5'/></g></svg>&nbsp;<span>" + expander.nextElementSibling.dataset.title + "</span>";
                            expander.style.borderBottomLeftRadius = "0";
                            expander.style.borderBottomRightRadius = "0";
                        }
                        else {
                            // close expander body
                            expander.nextElementSibling.style.display = "none";
                            expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg>&nbsp;<span>" + expander.nextElementSibling.dataset.title + "</span>";
                            expander.style.borderBottomLeftRadius = "6px";
                            expander.style.borderBottomRightRadius = "6px";
                        }
                    }
                }
            }, true);
            item.parentNode.insertBefore(divHeader, item);
            item.style.display = "none";
        }
    });
</script>

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

도움이 되길 바랍니다.

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

언급URL : https://stackoverflow.com/questions/17460116/how-can-i-expand-and-collapse-a-div-using-javascript

반응형