Open a specific accordion panel with an external anchor link

前端 未结 2 1240
温柔的废话
温柔的废话 2020-12-22 11:26

I have a bootstrap accordion setup and working fine.

I need to have links on external pages which will:

A) Take you to the specified panel within the accor

相关标签:
2条回答
  • 2020-12-22 11:30

    You can use url parameters and do it.

    Sample links:
    https://output.jsbin.com/talojodupa/1?panel=collapseOne
    https://output.jsbin.com/talojodupa/1?panel=collapseTwo

    jsbin link: https://jsbin.com/talojodupa/1/edit?html,js,output

    (function() {
        var searchTerm, panelContainerId;
        // Create a new contains that is case insensitive
        $.expr[':'].containsCaseInsensitive = function(n, i, m) {
            return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
        };
    
        $('#accordion_search_bar').on('change keyup paste click', function() {
            searchTerm = $(this).val();
            $('#accordion > .panel').each(function() {
                panelContainerId = '#' + $(this).attr('id');
                $(panelContainerId + ':not(:containsCaseInsensitive(' + searchTerm + '))').hide();
                $(panelContainerId + ':containsCaseInsensitive(' + searchTerm + ')').show();
            });
        });
      
      /* Function to get url parameter based on param name */
      function getUrlParameter(key) {
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var results = regex.exec(window.location.href);
        if (results == null)
          return "";
        else
          return unescape(results[1]).replace(/<script.*>.*<\/script>/g, "");
      }
      
      var panelId = getUrlParameter('panel');
      if(panelId){
        var $panel = $('#'+panelId);
        $panel.addClass('in');
    
        $('html,body').animate({
           scrollTop: $panel.offset().top},
        'slow');
      }
      
    }());

    0 讨论(0)
  • 2020-12-22 11:48

    You can try this:

    JS code: 
    
          $(function () {
                // check if there is a hash in the url
                if (window.location.hash != '') {
                    // show the panel based on the hash now.
                    $(window.location.hash + '.collapse').collapse('show');
                }
    
            });
    
    0 讨论(0)
提交回复
热议问题