Подтвердить что ты не робот

Как я могу развернуть и свернуть a <div> с помощью javascript?

Я создал список на своем сайте. Этот список создается циклом 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, который я пытаюсь манипулировать, по умолчанию является стиль = "display: none", и я хочу использовать javascript, чтобы сделать его видимым при нажатии.

"$ (this).find(" legend "). innerHTML" пытается передать в этом случае "Развернуть" в качестве аргумента в функции.

Вот 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>.

4b9b3361

Ответ 1

Итак, у вас есть два варианта:

  • Используйте jQuery UI-аккордеон - его приятно, легко и быстро. Подробнее здесь
  • Или, если вы все еще хотите сделать это самостоятельно, вы можете удалить 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/

Ответ 2

как насчет:

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 каждый раз.

Ответ 3

Здесь много проблем.

Я создал скрипку, которая работает для вас: http://jsfiddle.net/w9kSU/

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

Ответ 4

Итак, во-первых, ваш 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.

Ответ 5

Взгляните на функцию toggle() jQuery:

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

Кроме того, innerHTML функция jQuery .html().

Ответ 6

попробуйте 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

Вот мой пример анимации списка сотрудников с расширением описания.

<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

Поскольку у вас есть jQuery на странице, вы можете удалить этот атрибут onclick и функцию majorpointsexpand. Добавьте следующий script к нижней части страницы или, желательно, к внешнему файлу .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 находится внутри набора полей.

Ответ 9

Возможно, вы захотите взглянуть на этот простой метод 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, и он будет переключаться между отображением "none" или "block".

Исходный источник на snip2code - Как свернуть div в html

Ответ 10

Если вы использовали сборку данных-роли, например

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

то он закроет расширенный div

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

Ответ 11

<HTML><head><script language="javascript">function show(){document.getElementById("test").innerHTML='byeee';document.getElementById("test").style.height='200px';document.getElementById("test").style.width='200px';document.getElementById("test").style.transition='all 2s';}</script></head><body><style>div{width:100px;height:100px;border:2px solid blue;background-color:orange;}</style><div id="test"> hello </div><input type="button" value="okk" onclick="show()"/></body></HTML>