Таблица содержания прокручивается, и заголовок отображается позади заголовкаJquery

Программирование на jquery
Ответить
Anonymous
 Таблица содержания прокручивается, и заголовок отображается позади заголовка

Сообщение Anonymous »

Я создал таблицу содержания с помощью переключателя. Когда я нажимаю на основной переключатель, я перехожу к заголовку на той же странице, но прокручиваю до заголовка. Это мой код.

Код: Выделить всё

document.addEventListener('DOMContentLoaded', () => {
const tocList = document.getElementById('toc-list');
const headings = document.querySelectorAll('h2'); // Select only h2 headings

headings.forEach((heading, index) => {
const li = document.createElement('li');

const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'toc';
radio.value = heading.id || `heading-${index}`;
radio.style.display = 'none'; // Hide the radio button

// Ensure each heading has a unique id
heading.id = radio.value;

const label = document.createElement('label');
label.textContent = heading.textContent;
label.htmlFor = radio.value;

const a = document.createElement('a');
a.href = `#${radio.value}`;

// Add event listener to radio button
radio.addEventListener('change', () => {
document.getElementById(radio.value).scrollIntoView({ behavior: 'smooth' });
});

// Add event listener to anchor tag
a.addEventListener('click', (e) => {
e.preventDefault();
document.getElementById(radio.value).scrollIntoView({ behavior: 'smooth' });
radio.checked = true;

// Highlight the active link
document.querySelectorAll('.toc-list li').forEach(li => li.classList.remove('active'));
li.classList.add('active');
});

a.appendChild(label);
li.appendChild(radio);
li.appendChild(a);
tocList.appendChild(li);
});
});

Это мой код, пожалуйста, помогите
Я пробую это.
`document.addEventListener(' DOMContentLoaded', () => {
const tocList = document.getElementById('toc-list');
const headings = document.querySelectorAll('h2'); // Выбираем только заголовки h2

Код: Выделить всё

const createTOCItem = (heading, index) => {
const li = document.createElement('li');

const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'toc';
radio.value = heading.id || `heading-${index}`;
radio.style.display = 'none'; // Hide the radio button

// Ensure each heading has a unique id
heading.id = radio.value;

const label = document.createElement('label');
label.textContent = heading.textContent;
label.htmlFor = radio.value;

const a = document.createElement('a');
a.href = `#${radio.value}`;

// Function to calculate the scroll position
const scrollToHeading = (headingId) => {
const navbar = document.querySelector('.navbar'); // Adjust selector as needed to target your navbar
const navbarHeight = navbar ? navbar.offsetHeight : 0;
const scrollTarget = document.getElementById(headingId);
const topPosition = scrollTarget.getBoundingClientRect().top + window.pageYOffset - navbarHeight;

window.scrollTo({ top: topPosition, behavior: 'smooth' });
};

// Add event listener to radio button
radio.addEventListener('change', () => {
scrollToHeading(radio.value);
});

// Add event listener to anchor tag
a.addEventListener('click', (e) => {
e.preventDefault();
scrollToHeading(radio.value);
radio.checked = true;

// Highlight the active link
document.querySelectorAll('#toc-list li').forEach(li => li.classList.remove('active'));
li.classList.add('active');
});

a.appendChild(label);
li.appendChild(radio);
li.appendChild(a);
tocList.appendChild(li);
};

headings.forEach(createTOCItem);
});
и это.

Код: Выделить всё

document.addEventListener('DOMContentLoaded', () => {
const tocList = document.getElementById('toc-list');
const headings = document.querySelectorAll('h2'); // Select only h2 headings

headings.forEach((heading, index) =>  {
const li = document.createElement('li');

const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'toc';
radio.value = heading.id || `heading-${index}`; // Ensure unique IDs
radio.style.display = 'none'; // Hide radio button

heading.id = radio.value; // Assign unique ID to each heading

const label = document.createElement('label');
label.textContent = heading.textContent;
label.htmlFor = radio.value;

const a = document.createElement('a');
a.href = `#${radio.value}`;

// Combined click listener for radio and anchor tag
const combinedClickListener = (event) => {
event.preventDefault();
document.getElementById(radio.value).scrollIntoView({ behavior: 'smooth' });
radio.checked = true;

// Highlight the active link
document.querySelectorAll('.toc-list li').forEach(li => li.classList.remove('active'));
li.classList.add('active');

// Create container for heading content (modify based on your HTML structure)
const contentContainer = document.createElement('div');
contentContainer.classList.add('heading-content'); // Add CSS class for styling

// Fetch heading content (modify based on your HTML structure)
let headingContent;
if (heading.nextElementSibling && heading.nextElementSibling.classList.contains('heading-content')) {
headingContent = heading.nextElementSibling;
} else if (heading.parentNode.nextElementSibling && heading.parentNode.nextElementSibling.classList.contains('heading-content')) {
headingContent = heading.parentNode.nextElementSibling;
} else {
console.warn('Heading content not found. Update logic based on your HTML.');
}

// Remove existing content container (avoid duplicates)
const existingContainer = document.querySelector('.heading-content');
if (existingContainer) {
existingContainer.remove();
}

// Insert content container below navbar (adjust selector)
if (headingContent) {
const websiteNavbar = document.querySelector('.website-navbar'); // Replace with your navbar selector
if (websiteNavbar) {
const navbarHeight = websiteNavbar.offsetHeight; // Get navbar height
contentContainer.style.position = 'absolute';  // Absolute positioning
contentContainer.style.top = navbarHeight + 'px';  // Position below navbar
contentContainer.style.left = '0';
contentContainer.style.right = '0';
contentContainer.style.bottom = '0'; // Optional: Stretch to bottom
websiteNavbar.parentNode.insertBefore(contentContainer, websiteNavbar.nextSibling);
contentContainer.appendChild(headingContent.cloneNode(true)); // Clone to avoid modifying original structure
} else {
console.warn('Website navbar element not found. Update selector.');
}
}
};

radio.addEventListener('change', combinedClickListener);
a.addEventListener('click', combinedClickListener);

a.appendChild(label);
li.appendChild(radio);
li.appendChild(a);
tocList.appendChild(li);
});
});

но код не работает, пожалуйста помогите и решите мою проблему
`

Подробнее здесь: https://stackoverflow.com/questions/787 ... the-header
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Jquery»