0

Всем привет! Есть кнопки, по нажатию на которые появляется различный контент, по механике табов. В футере на небольшое оглавление я повесила якорные ссылки к этим табам, но, логично, что при переходе к якорю кнопка не получает фокус. Нужно чтоб получала, то есть при переходе по якорю раскрывался нужный контент. Это можно как-то сделать? Сss/js не принципиально, заранее спасибо!

1 ответ 1

0

Можно, с помощью JavaScript/jQuery

  1. Добавить уникальный id для каждой кнопки, который будет открывать нужный контент.
  2. В якорные ссылке добавить href с уникальным id кнопки к которой она относится.
  3. Через JavaScript либо jQuery искать все якорные ссылки на странице, и для каждой ссылки добавлять обработчик события клика, который при переходе по ссылке будет находить нужную кнопку и нажимать её

Реализация через JavaScript:

// Get all anchor links on the page
const anchors = document.querySelectorAll('a[href^="#"]');

// Add event listener for each anchor link
anchors.forEach(function (anchor) {
    anchor.addEventListener('click', function (e) {
        e.preventDefault(); // Prevent default behavior of the link
        
        // Get the id of the button to which the anchor link is related
        const targetId = this.getAttribute('href');

        // Find the target button by its id
        const targetButton = document.querySelector(targetId);

        // If the button is found, click it
        if (targetButton) {
            targetButton.click();
        }
    });
});

Реализация через jQuery:

// Add event listener for each anchor link
$('a[href^="#"]').click(function(e) {
    e.preventDefault(); // Prevent default behavior of the link

    // Get the id of the button to which the anchor link is related
    const targetId = $(this).attr('href');

    // Find the target button by its id
    const targetButton = $(targetId);

    // If the button is found, click it
    if (targetButton.length) {
        targetButton.click();
    }
});
2
  • Спасибо, мил человек!
    – elgreko
    30 мар в 21:09
  • А можно сделать то же самое, но не для button, а для div?
    – elgreko
    8 апр в 18:34

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.