Данная модификация позволяет добавить несколько отметок на карточку товара в Тильда. Например «Хит» и «Новинка»

Делаем 2 или 3 бейджа на карточке товара Тильда

Инструкция

Добавьте в "Товары" отметку на карточке товара в таком виде: Хит / Новинка
Вставьте код в блок "Другое" - Т123 в подвал вашего сайта
В настройках цветов и отступов вставьте свои значения цвета.
Код скопирован
Код для вставки:
Код написан на коленке, используйте осторожно. Не оказываем поддержку и доработку модификаций!
<!-- Делаем 2 или 3 бейджа на карточке товара Тильда | youx.agency -->
<!-- https://youx.agency/delaem-2-bejdzha-na-kartochke-tovara-tilda -->

<style>
/* Блокируем прыжки текста при загрузке страницы */
div:not([data-badge-done="true"]):has(> :empty):contains('/'),
span:not([data-badge-done="true"]):contains('/') {
    color: transparent !important;
}

/* Флекс-контейнер для выстраивания любого количества бейджей в ряд справа */
.badge-flex-container {
    display: flex !important;
    align-items: center !important;
    position: absolute !important;
    top: 0 !important;
    right: 0 !important;
    left: auto !important;
    z-index: 9999 !important;
}

/* Сброс стилей для внутренних плашек */
.badge-flex-container .my-split-badge {
    position: relative !important;
    top: auto !important;
    left: auto !important;
    right: auto !important;
    margin: 0 !important;
}
</style>

<script>
(function() {
    // ==========================================
    // НАСТРОЙКИ ЦВЕТОВ И ОТСТУПОВ
    // ==========================================
    var CONFIG = {
        badgeGap: '5px', // Отступ между плашками
        
        // 1. Бейдж первый (самый левый, например, TOP)
        badge1Bg: '#333333',   // Серый
        badge1Color: '#ffffff',
        
        // 2. Бейдж второй (по центру, например, NEW)
        badge2Bg: '#fff',   // Черный
        badge2Color: '#111'
        
        // 3. Третий бейдж (самый правый, SALE) автоматически 
        // заберет родной цвет из настроек дизайна самой Тильды!
    };
    // ==========================================

    function splitTildaBadges() {
        var allElements = document.querySelectorAll('div, span');
        
        allElements.forEach(function(badge) {
            if (badge.children.length === 0 && badge.innerText && badge.innerText.indexOf('/') !== -1) {
                
                if (badge.hasAttribute('data-badge-done')) return;
                badge.setAttribute('data-badge-done', 'true');
                
                // Режем строку по слэшам на массив слов
                var parts = badge.innerText.split('/').map(function(p) { return p.trim(); });
                
                var cardContainer = badge.closest('.t-store__card, .js-product, .t754__col, .t762__col, .t-store__card__imgwrapper, .t-slds__wrapper') || badge.parentElement;
                
                if (cardContainer && parts.length > 0) {
                    cardContainer.style.position = 'relative';
                    
                    // Создаем общую коробку
                    var flexContainer = document.createElement('div');
                    flexContainer.className = 'badge-flex-container';
                    flexContainer.style.setProperty('gap', CONFIG.badgeGap, 'important');
                    
                    var origComputed = window.getComputedStyle(badge);
                    var origTop = origComputed.top !== 'auto' ? origComputed.top : '15px';
                    var origRight = origComputed.right !== 'auto' ? origComputed.right : '15px';
                    flexContainer.style.setProperty('top', origTop, 'important');
                    flexContainer.style.setProperty('right', origRight, 'important');
                    
                    // Общая функция для стилизации и авто-ширины
                    var applyStyles = function(target) {
                        target.className = 'my-split-badge';
                        target.style.setProperty('padding', origComputed.padding, 'important');
                        target.style.setProperty('font-size', origComputed.fontSize, 'important');
                        target.style.setProperty('font-family', origComputed.fontFamily, 'important');
                        target.style.setProperty('font-weight', origComputed.fontWeight, 'important');
                        target.style.setProperty('border-radius', origComputed.borderRadius, 'important');
                        target.style.setProperty('line-height', origComputed.lineHeight, 'important');
                        target.style.setProperty('text-transform', origComputed.textTransform, 'important');
                        target.style.setProperty('letter-spacing', origComputed.letterSpacing, 'important');
                        
                        target.style.setProperty('width', 'auto', 'important'); 
                        if (origComputed.height && origComputed.height !== 'auto' && origComputed.height !== '0px') {
                            target.style.setProperty('height', origComputed.height, 'important');
                        }
                        
                        target.style.setProperty('display', 'inline-flex', 'important');
                        target.style.setProperty('align-items', 'center', 'important');
                        target.style.setProperty('justify-content', 'center', 'important');
                        target.style.setProperty('padding-left', '12px', 'important');
                        target.style.setProperty('padding-right', '12px', 'important');
                    };

                    // Динамически создаем плашки в зависимости от количества слов
                    parts.forEach(function(wordText, index) {
                        var newBadge = document.createElement('div');
                        newBadge.innerText = wordText;
                        applyStyles(newBadge);
                        
                        // Задаем цвета по порядку
                        if (parts.length === 3) {
                            // Если ввели ровно 3 слова
                            if (index === 0) { // Левый
                                newBadge.style.setProperty('background-color', CONFIG.badge1Bg, 'important');
                                newBadge.style.setProperty('color', CONFIG.badge1Color, 'important');
                            } else if (index === 1) { // Средний
                                newBadge.style.setProperty('background-color', CONFIG.badge2Bg, 'important');
                                newBadge.style.setProperty('color', CONFIG.badge2Color, 'important');
                            } else { // Правый (оригинальный цвет)
                                newBadge.style.setProperty('background-color', origComputed.backgroundColor, 'important');
                                newBadge.style.setProperty('color', origComputed.color, 'important');
                            }
                        } else {
                            // Откат на случай, если слов осталось 2
                            if (index === 0) {
                                newBadge.style.setProperty('background-color', CONFIG.badge2Bg, 'important');
                                newBadge.style.setProperty('color', CONFIG.badge2Color, 'important');
                            } else {
                                newBadge.style.setProperty('background-color', origComputed.backgroundColor, 'important');
                                newBadge.style.setProperty('color', origComputed.color, 'important');
                            }
                        }
                        
                        flexContainer.appendChild(newBadge);
                    });
                    
                    cardContainer.appendChild(flexContainer);
                    badge.style.setProperty('display', 'none', 'important');
                }
            }
        });
    }

    function loop() {
        splitTildaBadges();
        requestAnimationFrame(loop);
    }
    requestAnimationFrame(loop);
})();
</script>

Другие модификации

Made on
Tilda