jquery гармошка, открывающая коробку на основе href - PullRequest
9 голосов
/ 07 декабря 2009

Я пытаюсь открыть аккордеон по ссылке, которую я отправляю на страницу

Это мой URL

services.html # брэндинг

Я использую следующий код в голове:

 <script type="text/javascript">
      $(document).ready(function(){
     $('#accordion').accordion({collapsible: true, animated: 'slide', autoHeight: false, navigation: true, active : 'false'});
      });
  </script>

И гармошка выглядит так:

<div id="accordion">
<h3 id="branding"><a href="#">Branding</a></h3>
<div>
<p>Does your business have a</p>
</div>
<h3><a href="#print">Print</a></h3>
<div>
<p>Brochures</a></p>
</div>
</div>

Любая помощь будет принята с благодарностью ... http://docs.jquery.com/UI/Accordion

Ответы [ 5 ]

14 голосов
/ 08 декабря 2009

О, я вижу, Джефф сообщил, что текущая версия пользовательского интерфейса не работает, но у меня действительно было решение, использующее текущую версию ...

HTML

<div id="accordion">
 <h3><a href="#branding">Branding</a></h3>
 <div>
  <p>Does your business have a</p>
 </div>
 <h3><a href="#print">Print</a></h3>
  <div>
  <p>Brochures</p>
  </div>
</div>

Сценарий

$(function(){
 $('#accordion').accordion({
  collapsible: true,
  animated: 'slide',
  autoHeight: false,
  navigation: true
 });
 // open content that matches the hash
 var hash = window.location.hash;
 var thash = hash.substring(hash.lastIndexOf('#'), hash.length);
 $('#accordion').find('a[href*='+ thash + ']').closest('h3').trigger('click');
})

Первоначально я использовал a[href$=...], но изменил его на a[href*=...] ... либо будет работать


Обновление: опция navigation была удалена из jQuery UI 1.10.0 , поэтому используйте этот метод:

CSS

.accordion {
  position: relative;
}
.accordion .accordion-link {
  position: absolute;
  right: 1%;
  margin-top: 16px;
  z-index: 1;
  width: 12px;
  height: 12px;
  background: url(link.png) center center no-repeat; /* approx 12x12 link icon */
}

Сценарий

var hashId = 0,
  $accordion = $('#accordion');
if (window.location.hash) {
  $accordion.children('h3').each(function(i){
    var txt = $(this).text().toLowerCase().replace(/\s+/g,'_');
    this.id = txt;
    if (txt === window.location.hash.slice(1)) {
      hashId = i;
    }
  });
}

$accordion.accordion({
  active: hashId,
  animate: false,
  heightStyle: 'content',
  collapsible: true,
  create: function( event, ui ) {
    $accordion.children('h3').each(function(i){
      $(this).before('<a class="accordion-link link" data-index="' + i + '" href="#' + this.id + '"></a>');
    });
    $accordion.find('.accordion-link').click(function(){
      $accordion.accordion( "option", "active", $(this).data('index') );
    });
  }
});
2 голосов
/ 01 апреля 2015

Самый простой способ сделать это - использовать focusin.

     $(function() {
    $( "#accordion" ).accordion({
        event: "focusin"
    });
});


<div id="accordion">
<h3 id="section-1">Section 1</h3>
<div>
    <p>blaa </p>
</div>
<h3 id="section-2">Section 2</h3>
<div>
    <p>bla</p>
</div>

Вы можете получить ссылку на ту же или другую страницу, просто набрав

<a href "otherpage.html#section-1">click to go to section 1</a>
2 голосов
/ 07 декабря 2009

Плохая новость заключается в том, что плагин аккордеона в настоящее время не работает (по состоянию на 1.7.2, , который вы можете увидеть в билете # 4653 ). Хорошей новостью является то, что она исправлена, и вы уже можете скачать последнюю версию здесь - но будьте осторожны, это еще не стабильный выпуск!

Если вы используете код 1.8.1, функция навигации снова работает. Установка navigation: true заставит аккордеон автоматически открывать правильную панель, когда вы переходите по URL-адресу, который соответствует вашему фрагменту навигации (чтобы ваш пример работал: services.html#branding).

Я думаю, что вы также хотите добавить отсутствующий идентификатор к вашему тегу привязки, например:

<h3 id="branding"><a href="#branding">Branding</a></h3>

Наконец, вы можете использовать метод, описанный здесь , чтобы обновить URL вашей страницы, чтобы отразить, какая панель аккордеона была нажата без перезагрузки вашей страницы.

0 голосов
/ 02 октября 2014

Вот как это сделать ...

Он обновит хеш для вас в зависимости от того, что находится внутри ваших тегов h3.

Вы также можете указать индекс, установив атрибут в вашем аккордеонном контейнере div следующим образом: data-active-index = "2"

var initAccordion = function(_t) {
    _t.each(function() {
        var obj = {
            heightStyle: 'content',
            collapsible: true,
            beforeActivate: function( event, ui ) {
                window.location.hash = ui.newHeader.attr('id');
            }
        };
        // preset the active tab in html [0 = first tab]
        var attr = $(this).attr('data-active-index');
        obj.active = null;
        if(attr !== null && attr !== undefined) {
            obj.active = Number(attr);
        }
        // human readable ids        
        var hash = window.location.hash;
        $(this).find('>h3').each(function(i){
            this.id = $(this).text().toLowerCase().replace(/[^a-z0-9]/g, function(s) {
                var c = s.charCodeAt(0);
                if (c == 32) return '_'; // space
                return '';
            });
            if(hash && hash == '#'+this.id) {
                obj.active = i;
            }
        });
        $(this).accordion(obj);
    });
};initAccordion($(".accordion"));
0 голосов
/ 05 августа 2014

См .: Активировать раздел Аккордеон по URL-хэшу

Демо: найдено здесь .

TL; DR ... Вот код:

$( "#accordion" ).accordion({

    // Called when the widget instance is created.
    create: function( e, ui ) {

        // The accordion DOM element.
        var $this = $( this );

        // Triggered when the browser hash changes.
        $( window ).on( "hashchange", function( e ) {

                // The selector string used to find all accordion headers.
            var headers = $this.accordion( "option", "header" ),

                // The header we're looking for, based on the location hash.
                header = $( location.hash ),

                // The index of the header we're looking for.
                index = $this.find( headers ).index( header );

            // If there's a valid index, activate the accordion section.
            // Otherwise, do nothing.
            if ( index >= 0 ) {
                $this.accordion( "option", "active", index );    
            }

        });

        // Make sure this works on initial page load.
        $( window ).trigger( "hashchange" );

    }

});

… и HTML:

<div id="accordion">
  <h3 id="section1">Section 1</h3>
  <div>
    <p>
    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
    </p>
  </div>
  <h3 id="section2">Section 2</h3>
  <div>
    <p>
    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.
    </p>
  </div>
  <h3 id="section3">Section 3</h3>
  <div>
    <p>
    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
    </p>
    <ul>
      <li>List item one</li>
      <li>List item two</li>
      <li>List item three</li>
    </ul>
  </div>
  <h3 id="section4">Section 4</h3>
  <div>
    <p>
    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.
    </p>
    <p>
    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.
    </p>
  </div>
</div>

Хорошо сработало для моих нужд!

...