JavaScript аккордеон на Сайтах Google (классический)

1

Я пытаюсь создать аккордеон часто задаваемых вопросов на классической странице Сайтов Google, но не могу определить лучший маршрут.

Самое близкое, что у меня было, это копирование примера в w3schools.com в HTML-гаджет (код ниже). Однако панель не расширяется, и я не совсем понимаю часть кода.

Я также пробовал использовать пользовательский гаджет, но Google стал очень строгим, и не мог понять, как размещать.

Здесь тестовая страница с кодом: https://sites.google.com/a/cartomark.com/test/

Здесь код:

<style>
button.accordion {
background-color: #eee;
color: #444;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ddd;
}

button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
</style>
<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    } 
  }
}
</script>
Теги:
google-sites

1 ответ

1

Короткий ответ

Используйте гаджет HTML Box или создайте веб-приложение для скриптов Google Apps и вставьте его в качестве гаджета.

объяснение

Гаджет гаджета HTML

Один из вариантов - использовать гаджет HTML Box для вставки вашего кода HTML/CSS/JavaScript на страницу Сайтов Google. Одно из преимуществ этой альтернативы заключается в том, что высота будет автоматически изменена по содержанию.

Подробнее см. В разделе Создание настраиваемых макетов страниц или гаджетов, но имейте в виду, что не все работает так же, как и в других местах. В этом конкретном случае выглядит, что HTML Box не поддерживает nextElementSibling. Обходным путем для этого является замена

var panel = this.nextElementSibling;

от

var panel = nextElementSibling(this);

или же

var panel = this.nextElementSibling || nextElementSibling(this);

и добавить в конец добавить

function nextElementSibling( el ) {
    do { el = el.nextSibling } while ( el && el.nodeType !== 1 );
    return el;
}

Я взял эту идею от ответа на user113716 к портативности nextElementSibling/NextSibling

ПРИМЕЧАНИЕ. Я разместил вопрос на официальном справочном форуме Сайтов Google, спрашивая, почему this.nextElementSibling возвращает null.

Скриншоты

Изображение 174551

Изображение 174551

Код

<style>
  button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
  }
  
  button.accordion.active,
  button.accordion:hover {
    background-color: #ddd;
  }
  
  button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
  }
  
  button.accordion.active:after {
    content: "\2212";
  }
  
  div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
  }
</style>

<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button id="button_1" class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button id="button_2" class="accordion">Section 2</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button id="button_3" class="accordion">Section 3</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<script>
  var acc = document.getElementsByClassName("accordion");
  var i;

  for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
      this.classList.toggle("active");
      var panel = this.nextElementSibling || nextElementSibling(this);
      if (panel.style.maxHeight) {
        panel.style.maxHeight = null;
      } else {
        panel.style.maxHeight = panel.scrollHeight + "px";
      }
    }
  }


  function nextElementSibling(el) {
    do {
      el = el.nextSibling
    } while (el && el.nodeType !== 1);
    return el;
  }
</script>

Веб-приложение для скриптов Google Apps

Другой альтернативой является создание веб-приложения для скриптов Google Apps, вставка которого в качестве гаджета Google Apps Script. "Проблема" с этой альтернативой заключается в том, что ее высота статична. Гаджет имеет возможность показывать вертикальную полосу прокрутки, когда это потребуется. Подробные инструкции о том, как это сделать, см. В моем ответе " Принять сценарии приложений" с параметрами с классического сайта google

  • 0
    Спасибо за попытку. Я использовал гаджет HTML Box. Ваши панели расширяются? У меня такой же результат, как и у вас, но высота панелей не меняется. Пример: sites.google.com/a/cartomark.com/test
  • 0
    Нет, мои панели не расширяются. Я думаю, что проблема из-за Кахи . Один из вариантов - создать веб-приложение Google Apps Script и вставить его в качестве гаджета Сайтов Google, но проблема заключается в том, что высота не увеличивается или не уменьшается динамически, поэтому вам необходимо установить высоту в настройках гаджета.
Показать ещё 3 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню