MediaWiki:Common.js: различия между версиями

мНет описания правки
мНет описания правки
Строка 336: Строка 336:
// Функция для подсветки ячеек в таблице при наведении
// Функция для подсветки ячеек в таблице при наведении
function applyHighlighting() {
function applyHighlighting() {
// Проверка, является ли устройство мобильным, выходим из функции если да
    // Проверка, является ли устройство мобильным, если да — функция не выполняется
     if (/Mobi|Android/i.test(navigator.userAgent)) {
     if (/Mobi|Android/i.test(navigator.userAgent)) {
         return;
         return;
     }
     }
      
 
     // Находим все таблицы с классом 'wikitable', кроме тех, что имеют класс 'no-highlight-table'
     var tables = document.querySelectorAll('.wikitable:not(.no-highlight-table)');
     var tables = document.querySelectorAll('.wikitable:not(.no-highlight-table)');


    // Проходим по каждой таблице
     Array.prototype.forEach.call(tables, function(table) {
     Array.prototype.forEach.call(tables, function(table) {
         var tbody = table.querySelector('tbody');
         var tbody = table.querySelector('tbody');
         var thead = table.querySelector('thead');
         var thead = table.querySelector('thead');


         // Проверяем, что tbody существует
         // Проверяем, что тело таблицы существует
         if (tbody) {
         if (tbody) {
            // Получаем все строки <tr> внутри tbody, исключая строки, содержащие вложенные таблицы
             var rows = Array.prototype.slice.call(tbody.querySelectorAll('tr')).filter(function(row) {
             var rows = Array.prototype.slice.call(tbody.querySelectorAll('tr')).filter(function(row) {
                 return !row.querySelector('table');
                 return !row.querySelector('table');
             });
             });


             // Пропускаем первую строку, если thead нет
             // Пропускаем первую строку, если нет заголовка таблицы (thead)
             var topLevelRows = thead ? rows : rows.slice(1);
             var topLevelRows = thead ? rows : rows.slice(1);


Строка 359: Строка 362:
             var hasTooManyRowspan = false;
             var hasTooManyRowspan = false;


            // Проходим по строкам первого уровня
             topLevelRows.forEach(function(row) {
             topLevelRows.forEach(function(row) {
                 var cells = Array.prototype.slice.call(row.querySelectorAll('td, th'));
                 var cells = Array.prototype.slice.call(row.querySelectorAll('td, th')); // Получаем все ячейки строки


                // Проверяем, есть ли больше двух ячеек с атрибутом rowspan
                 var rowspanCount = cells.filter(function(cell) {
                 var rowspanCount = cells.filter(function(cell) {
                     return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1';
                     return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1';
                 }).length;
                 }).length;


                // Если таких ячеек больше двух, прерываем выполнение
                 if (rowspanCount > 2) {
                 if (rowspanCount > 2) {
                     hasTooManyRowspan = true;
                     hasTooManyRowspan = true;
Строка 371: Строка 377:
                 }
                 }


                // Проверяем, есть ли корректные ячейки с rowspan на краю строки (первый или последний элемент)
                 var hasValidRowspanEdge = cells.some(function(cell, index) {
                 var hasValidRowspanEdge = cells.some(function(cell, index) {
                     return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1' && (index === 0 || index === cells.length - 1);
                     return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1' && (index === 0 || index === cells.length - 1);
                 });
                 });


                // Если ячейки с rowspan находятся не на краю, устанавливаем флаг ошибки
                 if (!hasValidRowspanEdge && cells.some(function(cell, index) {
                 if (!hasValidRowspanEdge && cells.some(function(cell, index) {
                     return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1' && index > 0 && index < cells.length - 1;
                     return cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1' && index > 0 && index < cells.length - 1;
Строка 382: Строка 390:
             });
             });


            // Если есть некорректные строки с rowspan или слишком много rowspan, выходим
             if (hasTooManyRowspan || hasInvalidRowspan) return;
             if (hasTooManyRowspan || hasInvalidRowspan) return;


            // Проходим по каждой строке для добавления событий подсветки
             topLevelRows.forEach(function(row) {
             topLevelRows.forEach(function(row) {
                 var cells = Array.prototype.slice.call(row.querySelectorAll('td, th'));
                 var cells = Array.prototype.slice.call(row.querySelectorAll('td, th'));
                 var originalStyles = cells.map(function(cell) {
                 var originalStyles = cells.map(function(cell) {
                    // Сохраняем оригинальные стили каждой ячейки
                     return {
                     return {
                         backgroundColor: getComputedStyle(cell).backgroundColor,
                         backgroundColor: getComputedStyle(cell).backgroundColor,
Строка 393: Строка 404:
                 });
                 });


                // Добавляем события 'mouseover' и 'mouseout' для подсветки
                 cells.forEach(function(cell, index) {
                 cells.forEach(function(cell, index) {
                     if (cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1') return;
                     if (cell.hasAttribute('rowspan') && cell.getAttribute('rowspan') !== '1') return;


                    // Добавляем обработчик события при наведении мыши
                     cell.addEventListener('mouseover', function() {
                     cell.addEventListener('mouseover', function() {
                         cells.forEach(function(innerCell, innerIndex) {
                         cells.forEach(function(innerCell, innerIndex) {
                             if (!innerCell.hasAttribute('rowspan') || innerCell.getAttribute('rowspan') === '1') {
                             if (!innerCell.hasAttribute('rowspan') || innerCell.getAttribute('rowspan') === '1') {
                                // Увеличиваем яркость фона и текста ячейки при наведении
                                 innerCell.style.backgroundColor = brightenColor(originalStyles[innerIndex].backgroundColor, 1.04);
                                 innerCell.style.backgroundColor = brightenColor(originalStyles[innerIndex].backgroundColor, 1.04);
                                 innerCell.style.color = brightenColor(originalStyles[innerIndex].color, 1.04);
                                 innerCell.style.color = brightenColor(originalStyles[innerIndex].color, 1.04);
Строка 405: Строка 419:
                     });
                     });


                    // Добавляем обработчик события, когда мышь уходит с ячейки
                     cell.addEventListener('mouseout', function() {
                     cell.addEventListener('mouseout', function() {
                         cells.forEach(function(innerCell, innerIndex) {
                         cells.forEach(function(innerCell, innerIndex) {
                             if (!innerCell.hasAttribute('rowspan') || innerCell.getAttribute('rowspan') === '1') {
                             if (!innerCell.hasAttribute('rowspan') || innerCell.getAttribute('rowspan') === '1') {
                                // Восстанавливаем оригинальные стили после наведения
                                 innerCell.style.backgroundColor = originalStyles[innerIndex].backgroundColor;
                                 innerCell.style.backgroundColor = originalStyles[innerIndex].backgroundColor;
                                 innerCell.style.color = originalStyles[innerIndex].color;
                                 innerCell.style.color = originalStyles[innerIndex].color;
Строка 454: Строка 470:
}
}
var tables = document.querySelectorAll('.wikitable');
var tables = document.querySelectorAll('.wikitable');
    if (tables.length > 0) {
if (tables.length > 0) {
        applyHighlighting();
    setTimeout(function() {
    }
        applyHighlighting();
    }, 500); // Задержка в 0.5 секунд до запуска
}
});
});
/*WikiEditor/Викификатор*/
/*WikiEditor/Викификатор*/