Единый форум поддержки

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » Единый форум поддержки » Новые возможности форумов » Запросы по скриптам #11


Запросы по скриптам #11

Сообщений 1701 страница 1708 из 1708

1

Предыдущая тема - Запросы по скриптам[9]

Инструменты для поиска и редактирования стиля (скриптов).

Как с помощью браузера можно определить элемент дизайна.

Каталог скриптов/CSS

Полезные скрипты, необходимые темы для новичков, а также ссылки на сайты рассказывающие что такое НТМЛ и CSS.

Типовые Вопросы (ЧаВо)

Ответы на часто задаваемые вопросы.

Как задавать вопросы! Разница между стилем и скриптом. ( Советы)

Плюс к названию темы еще и Памятка.

Предыдущая часть темы: Запросы по скриптам[10]

+1

1701

Merlin777

Код:
<script>$('.post-author .pa-posts').each(function(){var uid=$(this).closest('.post').attr('data-user-id');$(this).find('.fld-name').html('<a href="/search.php?action=show_user_posts&user_id='+uid+'">'+$(this).find('.fld-name').text().split(':')[0]+'</a>:')})</script>

+2

1702

Deff написал(а):

Удовлетворил просьбы фиксировать созданные темы,
(Было пожелание учета бонусов по созданным темам, не сообщениям)

Счетчик тем, создаваемых юзером
https://sa.uploads.ru/gnPv7.jpg
(Кликабельно)

Установка

1. Создаём в Администрировании - Поля профиля - Новое поле, с точным названием: Создано тем - Cкриншот настроек этого поля: http://sa.uploads.ru/3CHkQ.jpg
2. Перемещаем его над полем сообщения (за крестик) http://sa.uploads.ru/CyKHt.jpg

3. В самый верх, HTML верх устанавливаем скрипт:

<!-- Счетчик тем, созданных юзером -->
<noscript><link rel="stylesheet" type="text/css" href="https://forumstatic.ru/files/0013/66/53/39517.css" /></noscript>
<script type="text/javascript" src="https://forumstatic.ru/files/0013/66/53/67954.js"></script>

PS: Отсчет тем ведётся с момента установки скрипта!   Администраторы, при желании, могут изменять цифру кол-ва тем в доп. поле Профиля юзера на вкладке "Дополнительно".
Счётчик считает только в форумах, у которых включён счетчик сообщений!(см настройки нужного форума)

Тестируем - отписываемся


Счётчик тем не увеличивается.

0

1703

Merlin777
Попробуйте переместить скрипт в самый верх HTML верх, а также проверьте, что в тех форумах, где проверяете подсчёт, включен счётчик сообщений (Администрирование - Форумы).

+1

1704

Стиль тёмной темы для предустановленного стиля форума "Mybb vBullitin mix".

Как установить: в админ. панели меню "Формы", далее в любую панель HTML, я рекомендую  в самый низ окна HTML низ, там оно мешать ничему не будет.

Посмотреть код
Код:
<!-- Тёмная тема -->
<style>#html-header{position:relative}.StyleSwitch{height:20px;width:20px;position:absolute;z-index:1000;right:5px;top:50px;border-radius:50%;cursor:pointer;box-shadow:0 0 10px rgba(0,0,0,.7);transition:.1s ease}.StyleSwitch:hover{opacity:.8}.StyleSwitch.St{background:#426B9A url(https://forumstatic.ru/files/0016/a6/f8/90261.png) center center no-repeat!important;background-size:16px!important}.StyleSwitch.My{background:#6996CA url(https://forumstatic.ru/files/0016/a6/f8/22564.png) center center no-repeat!important;background-size:16px!important}body.dark-theme .post .post-body::before{border-color:transparent #4a5b70 transparent transparent !important}body.dark-theme .post .post-body::after{border-color:transparent #2d3748 transparent transparent !important}body.dark-theme .postVoters strong{background:#c0c0c0;padding:2px 4px;border-radius:4px;color:#000}body.dark-theme .punbb .post-content p a{background:rgba(255,255,255,0.1);border-radius:3px;padding:2px}body.dark-theme .punbb .post-content p a:hover{color:teal}</style><script>(function(){var style='https://forumstatic.ru/files/001a/f0/7d/20423.css?v=2';style='<link rel="stylesheet" id="StyleAdd" type="text/css" href="'+style+'"/>';function setStyle(){$('link[rel="stylesheet"]:last').after(style);$('.StyleSwitch').removeClass('St').addClass('My');$('.StyleSwitch').attr('title','Стандартный стиль');$('body').addClass('dark-theme')}$('#html-header').prepend('<span class="StyleSwitch St" title="Затемненный стиль"></span>');$('.StyleSwitch').tipsy({fade:true,gravity:'nw'});if($getCookie('StyleSwitch')){setStyle();}$('.StyleSwitch.St').live('click',function(){$setCookie('StyleSwitch','My',30*3600*24*30*1000);setStyle();});$('.StyleSwitch.My').live('click',function(){$('link#StyleAdd').remove();$deleteCookie('StyleSwitch');$('.StyleSwitch').addClass('St').removeClass('My');$('.StyleSwitch').attr('title','Затемненный стиль');$('body').removeClass('dark-theme');});})();</script>
<!-- Конец тёмной темы -->

Это код в в "минифицированном" виде, чтобы занимал меньше места при загрузке. Полная версия с комментариями выглядит так:

Посмотреть код
Код:
<!-- Тёмная тема и вспомогательные стили -->
<style>
/* ===== Переключатель темы ===== */
#html-header {
    position: relative; /* Чтобы кнопка StyleSwitch позиционировалась относительно header */
}
.StyleSwitch {
    height: 20px;
    width: 20px;
    position: absolute;
    z-index: 1000;
    right: 5px; /* Отступ справа */
    top: 50px;  /* Отступ сверху */
    border-radius: 50%; /* Круглая кнопка */
    cursor: pointer;
    box-shadow: 0 0 10px rgba(0,0,0,.7); /* Тень для объёма */
    transition: .1s ease; /* Плавная анимация при наведении */
}
.StyleSwitch:hover { opacity: .8; } /* Лёгкое затемнение при наведении */
.StyleSwitch.St {
    background: #426B9A url(https://forumstatic.ru/files/0016/a6/f8/22564.png) center center no-repeat!important;
    background-size: 16px!important; /* Иконка стандартного стиля */
}
.StyleSwitch.My {
    background: #6996CA url(https://forumstatic.ru/files/0016/a6/f8/90261.png) center center no-repeat!important;
    background-size: 16px!important; /* Иконка тёмного стиля */
}

/* ===== Треугольники (только для тёмной темы) ===== */
body.dark-theme .post .post-body::before {
    border-color: transparent #4a5b70 transparent transparent !important; /* тёмный фон треугольника */
}
body.dark-theme .post .post-body::after {
    border-color: transparent #2d3748 transparent transparent !important; /* тёмная окантовка */
}

/* ===== "Сказали спасибо" (только для тёмной темы) ===== */
body.dark-theme .postVoters strong {
    background: #c0c0c0; /* серебристый фон */
    padding: 2px 4px;
    border-radius: 4px;
    color: #000; /* чёрный текст */
}

/* ===== Подсветка ссылок в постах (только для тёмной темы) ===== */
body.dark-theme .punbb .post-content p a {
    background: rgba(255,255,255,0.1); /* мягкий светлый фон */
    border-radius: 3px;
    padding: 2px;
}
body.dark-theme .punbb .post-content p a:hover { color: teal; } /* цвет текста при наведении */
</style>

<script type="text/javascript">
(function () {
    var style = 'https://forumstatic.ru/files/001a/f0/7d/73291.css?v=45'; // Ссылка на внешний CSS для тёмной темы
    style = '<link rel="stylesheet" id="StyleAdd" type="text/css" href="'+style+'"/>';

    /* ===== Функция включения тёмного стиля ===== */
    function setStyle () {
        $('link[rel="stylesheet"]:last').after(style); // Подключаем внешний CSS
        $('.StyleSwitch').removeClass('St').addClass('My'); // Меняем иконку кнопки
        $('.StyleSwitch').attr('title','Стандартный стиль'); // Подпись кнопки
        $('body').addClass('dark-theme'); // Добавляем класс тёмной темы
    }

    /* ===== Добавляем кнопку в HTML ===== */
    $('#html-header').prepend('<span class="StyleSwitch St" title="Затемненный стиль"></span>');
    $('.StyleSwitch').tipsy({fade: true, gravity: 'nw'}); // Подсказка при наведении

    if($getCookie('StyleSwitch')) { setStyle (); } // Если включена тёмная тема, применяем сразу

    /* ===== Событие клика по кнопке для включения ===== */
    $('.StyleSwitch.St').live('click', function () {
        $setCookie('StyleSwitch','My',30*3600*24*30*1000); // Сохраняем cookie на 30 дней
        setStyle ();
    });  

    /* ===== Событие клика по кнопке для выключения ===== */
    $('.StyleSwitch.My').live('click', function () {
        $('link#StyleAdd').remove(); // Убираем подключённый CSS
        $deleteCookie('StyleSwitch'); // Удаляем cookie
        $('.StyleSwitch').addClass('St').removeClass('My'); // Меняем иконку на стандартную
        $('.StyleSwitch').attr('title','Затемненный стиль');
        $('body').removeClass('dark-theme'); // Убираем класс тёмной темы
    });
})();
</script>
<!-- Конец тёмной темы -->

Тёмная тема включается кнопкой, которая в десктопном разрешении экрана находится справа вверху (значок синей лампочки). В мобильном виде эта кнопка скрыта.

Достоинства: Это тёмная тема 🖤  которая реально выглядит неплохо (как в стандартном виде, так и со всеми улучшениями кода, что я добавил себе на форум)  :)
Код выложен в исходном виде, поэтому вы можете сами его легко модифицировать  :)

Недостатки: код подключает к себе внешний стиль по адресу https://forumstatic.ru/files/001a/f0/7d/73291.css
Это стиль от господина @Reysler  , насколько я понимаю, для сервиса RusFF и там много "лишнего для платформы MyBB.ru. Я не знаю, что именно оттуда можно удалить как ненужное и без последствий.
В минифицированном виде он просто сжат в файл https://forumstatic.ru/files/001a/f0/7d/20423.css и именно его "тянет" минифицированный скрипт.

P.S. Ещё кое что.
После установки тёмной темы, может наблюдаться мелькание белого пустого фона браузера перед загрузкой тёмного варианта страницы, это раздражает :)

Это очень распространённая проблема при использовании тёмных тем на сайтах: "белая вспышка" (или "flash of unstyled content" — FOUC), которая происходит до применения CSS, особенно когда тёмная тема подключается через JavaScript после загрузки страницы.

Мы не имеем доступа к непосредственно коду страниц форума, поэтому применим обходной путь (вставим затеняющий экран после загрузки DOM и основных CSS, но строго до загрузки кода тёмной темы).

В самый верх окна HTML верх вставить код:

Показать код
Код:
<!-- Тёмная тема без вспышки -->
<style id="dark-loader-style" disabled>
  #dark-loader {
    position: fixed;
    z-index: 99999;
    top: 0; left: 0;
    width: 100vw;
    height: 100vh;
    background: #121212;
    pointer-events: none;
  }
</style>

<script>
// Вставляем затемняющий экран сразу, если активна тёмная тема
(function () {
  if (document.cookie.indexOf('StyleSwitch=My') !== -1) {
    document.getElementById('dark-loader-style').disabled = false;
    var loader = document.createElement('div');
    loader.id = 'dark-loader';
    document.body.appendChild(loader);

    window.addEventListener('load', function () {
      setTimeout(() => {
        document.getElementById('dark-loader')?.remove();
      }, 50); // Можете увеличить до 100–200, если фон всё равно мелькает
    });
  }
})();
</script>

<style>
/* Стили кнопки и темы */
#html-header{position:relative}
.StyleSwitch{height:20px;width:20px;position:absolute;z-index:1000;right:5px;top:50px;border-radius:50%;cursor:pointer;box-shadow:0 0 10px rgba(0,0,0,.7);transition:.1s ease}
.StyleSwitch:hover{opacity:.8}
.StyleSwitch.St{background:#426B9A url(https://forumstatic.ru/files/0016/a6/f8/90261.png) center center no-repeat!important;background-size:16px!important}
.StyleSwitch.My{background:#6996CA url(https://forumstatic.ru/files/0016/a6/f8/22564.png) center center no-repeat!important;background-size:16px!important}
body.dark-theme .post .post-body::before{border-color:transparent #4a5b70 transparent transparent !important}
body.dark-theme .post .post-body::after{border-color:transparent #2d3748 transparent transparent !important}
body.dark-theme .postVoters strong{background:#c0c0c0;padding:2px 4px;border-radius:4px;color:#000}
body.dark-theme .punbb .post-content p a{background:rgba(255,255,255,0.1);border-radius:3px;padding:2px}
body.dark-theme .punbb .post-content p a:hover{color:teal}
</style>
<!-- Тёмная тема без вспышки -->

P.P.S. Можно добавить кнопку включения тёмной темы для мобильного режима просмотра.

Показать код
Код:
<!--🌙 Плавающий переключатель тёмной темы (фиксированно с регулировкой от верха) -->
<script>
(function(){
  var topOffset = 270; // ⬆️ Положение кнопки от верха (можно менять)
  var mobileMaxWidth = 600; // 📱 Порог ширины для мобильного

  function isMobile(){ return window.innerWidth <= mobileMaxWidth; }
  function isHome(){ return location.pathname === '/' || location.pathname.endsWith('index.php'); }

  function updateButtonTheme(btn) {
    const isDark = document.cookie.includes('StyleSwitch=My');
    btn.style.background = isDark
      ? '#6996CA url("https://forumstatic.ru/files/0016/a6/f8/22564.png") center/50% no-repeat'
      : '#426B9A url("https://forumstatic.ru/files/0016/a6/f8/90261.png") center/50% no-repeat';
    btn.title = isDark ? 'Светлая тема' : 'Тёмная тема';
  }

  function createMobileSwitch(){
    if (!isMobile() || !isHome()) return;
    if (document.getElementById('mobile-style-switch')) return;

    const btn = document.createElement('div');
    btn.id = 'mobile-style-switch';
    document.body.appendChild(btn);

    const style = document.createElement('style');
    style.textContent = `
      #mobile-style-switch {
        position: fixed;
        top: ${topOffset}px;
        right: 15px;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #426B9A url('https://forumstatic.ru/files/0016/a6/f8/90261.png') center/50% no-repeat;
        box-shadow: 0 0 8px rgba(0,0,0,0.6);
        z-index: 10000;
        cursor: pointer;
        transition: transform 0.2s ease;
      }
      #mobile-style-switch:active {
        transform: scale(0.9);
      }
    `;
    document.head.appendChild(style);

    updateButtonTheme(btn); // выставляем начальное состояние

    btn.addEventListener('click', function(){
      const desktopBtn = document.querySelector('.StyleSwitch');
      if (desktopBtn) {
        desktopBtn.click();
        setTimeout(() => updateButtonTheme(btn), 100); // ⚡ небольшая задержка, чтобы тема успела примениться
      }
    });
  }

  function waitForBody(){
    if (document.body){
      createMobileSwitch();
    } else {
      setTimeout(waitForBody, 50);
    }
  }
  waitForBody();

  window.addEventListener('resize', createMobileSwitch);
})();
</script>
<!--🌙 Плавающий переключатель тёмной темы (фиксированно с регулировкой от верха) -->

После установки всех кодов, сохраните их в админ панели :) , потом зайдите на свой форум и перезагрузите его через Ctrl+F5.
Если это не поможет, очистите кэш в вашем браузере за последний час.

Отредактировано Merlin777 (Сб, 27 Сен 2025 09:52:25)

0

1705

Merlin777 написал(а):

Это стиль от господина @Reysler  , насколько я понимаю, для сервиса RusFF и там много "лишнего для платформы MyBB.ru.

Ничего подобного :) Судя по коду, он был написал для тёмного стиля этого форума технической поддержки.

+1

1706

Приветствую! Интересует данный скрипт, но хотелось бы похожий с некоторой доработкой.
Можно ли сделать вместо автопрокрутки прокрутку вручную со стрелочками? Типа как в VK

Скрипт автопрокрутки картинок для HTML в сообщениях

Код:
<!-- Прокрутка картинок для HTML в сообщениях--><div class="SL" style="width:300px;text-align:center"></div><script>var arraySL = [ //Cписок ссылок на Изо:'https://forumstatic.ru/files/0013/44/56/61036.png','https://forumstatic.ru/files/0013/44/56/73446.png','https://forumstatic.ru/files/0013/44/56/54143.png','https://forumstatic.ru/files/0013/44/56/21344.png','https://forumstatic.ru/files/0013/44/56/87837.png']var heightSL = 'auto'; //'auto'//'386px'; //Высота в пикселах или 'auto';var SLtime = 5; //Время в секундах;</script><script  type="text/javascript" src="https://forumstatic.ru/files/0013/44/56/17756.js"></script>

Скрипты от пользователей 3 (пост 558)

Отредактировано Laurita (Чт, 2 Окт 2025 17:30:03)

0

1707

[html]<!-- Слайдер -->
<div class="SL" style="width:100%;max-width:300px;text-align:center;position:relative;margin:auto;">
  <button class="sl-arrow left"><</button>
  <img class="sl-image" src="" style="width:100%;height:auto;" />
  <button class="sl-arrow right">></button>
  <div class="sl-dots"></div>
  <button class="sl-autoplay-toggle">▶</button>
</div>

<script>
(function() {
  const arraySL = [
    'https://forumstatic.ru/files/0013/44/56/61036.png',
    'https://forumstatic.ru/files/0013/44/56/73446.png',
    'https://forumstatic.ru/files/0013/44/56/54143.png',
    'https://forumstatic.ru/files/0013/44/56/21344.png',
    'https://forumstatic.ru/files/0013/44/56/87837.png'
  ];

  const slider = document.querySelector('.SL');
  const imgElement = slider.querySelector('.sl-image');
  const leftBtn = slider.querySelector('.sl-arrow.left');
  const rightBtn = slider.querySelector('.sl-arrow.right');
  const dotsContainer = slider.querySelector('.sl-dots');
  const autoplayBtn = slider.querySelector('.sl-autoplay-toggle');

  let currentIndex = 0;
  let autoSlide = null;
  let isAutoplay = false;
  let startX = 0;
  let endX = 0;

  // Создание дот-индикатора
  arraySL.forEach((_, i) => {
    const dot = document.createElement('span');
    dot.className = 'sl-dot';
    dot.addEventListener('click', () => {
      currentIndex = i;
      updateImage();
    });
    dotsContainer.appendChild(dot);
  });

  function updateDots() {
    dotsContainer.querySelectorAll('.sl-dot').forEach((dot, i) => {
      dot.style.opacity = i === currentIndex ? '1' : '0.5';
    });
  }

  function updateImage() {
    imgElement.style.opacity = 0;
    setTimeout(() => {
      imgElement.src = arraySL[currentIndex];
      imgElement.style.opacity = 1;
      updateDots();
    }, 200);
  }

  // Кнопки
  leftBtn.addEventListener('click', () => {
    currentIndex = (currentIndex - 1 + arraySL.length) % arraySL.length;
    updateImage();
  });

  rightBtn.addEventListener('click', () => {
    currentIndex = (currentIndex + 1) % arraySL.length;
    updateImage();
  });

  // Автопрокрутка
  function startAutoplay() {
    if (!isAutoplay) {
      autoSlide = setInterval(() => {
        currentIndex = (currentIndex + 1) % arraySL.length;
        updateImage();
      }, 3000);
      autoplayBtn.textContent = '⏸';
      isAutoplay = true;
    }
  }

  function stopAutoplay() {
    clearInterval(autoSlide);
    autoplayBtn.textContent = '▶';
    isAutoplay = false;
  }

  autoplayBtn.addEventListener('click', () => {
    if (isAutoplay) stopAutoplay();
    else startAutoplay();
  });

  // Свайпы для мобильных
  slider.addEventListener('touchstart', e => {
    startX = e.touches[0].clientX;
  });
  slider.addEventListener('touchend', e => {
    endX = e.changedTouches[0].clientX;
    if (startX - endX > 50) rightBtn.click();
    if (endX - startX > 50) leftBtn.click();
  });

  // Инициализация
  updateImage();
})();
</script>

<style>
.SL {
  position: relative;
  width: 100%;
  max-width: 300px;
  margin: auto;
  text-align: center;
}

.sl-arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(0,0,0,0.4);
  color: white;
  border: none;
  font-size: 18px;
  font-weight: bold;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.3s ease;
  user-select: none;
}

.sl-arrow.left { left: 10px; }
.sl-arrow.right { right: 10px; }

.SL:hover .sl-arrow { opacity: 1; }
.sl-arrow:hover { background: rgba(0,0,0,0.7); }

.sl-image {
  width: 100%;
  height: auto;
  transition: opacity 0.5s ease;
  display: block;
}

.sl-dots {
  text-align: center;
  margin-top: 5px;
}

.sl-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(0,0,0,0.5);
  margin: 0 3px;
  cursor: pointer;
  transition: opacity 0.3s;
}

.sl-autoplay-toggle {
  position: absolute;
  top: 5px;
  right: 5px;
  background: rgba(0,0,0,0.4);
  color: white;
  border: none;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 16px;
  line-height: 28px;
  text-align: center;
  z-index: 2;
  user-select: none;
}

.sl-autoplay-toggle:hover { background: rgba(0,0,0,0.7); }
</style>
[/html]

@Laurita

🛠️Что добавлено и улучшено:

✅Добавлены стрелочки прокрутки (для десктопного режима - при наведении, для мобильного - постоянно).

✅Автопрокрутка: с кнопкой включения/выключения в верхнем правом углу.

✅Плавная анимация: transition: opacity 0.5s ease.

✅Дот-индикатор: под картинкой, кликабельный.

✅На мобильных: перелистывание кнопками или свайпами (пальцем).

✅Адаптивность: max-width: 300px; width: 100%.

📝Код: полностью обернут в IIFE, let/const используются корректно.

+1

1708

Merlin777 написал(а):

🛠️Что добавлено и улучшено:

Merlin777, спасибо огромное. То, что нужно.
Буду тестить

+1


Вы здесь » Единый форум поддержки » Новые возможности форумов » Запросы по скриптам #11