ВРЕМЯ/ЧАСЫ

Показывает текущее время и день недели на странице

目前为 2025-03-04 提交的版本。查看 最新版本

// ==UserScript==
// @name        ВРЕМЯ/ЧАСЫ
// @namespace   AceScript Scripts
// @match       *://*/*
// @grant       none
// @version     1.6
// @author      DELFION
// @inject-into auto
// @license     MIT
// @description Показывает текущее время и день недели на странице
// ==/UserScript==

(function() {
  "use strict";

  // Функция создаёт элемент для отображения времени
  // Function creates an element to display the time
  function createTimeDisplay() {
    const timeElement = document.createElement("div");
    timeElement.classList.add("time-display");

    // Создаём элементы для отображения часов, минут и дня недели
    // Creating elements to display hours, minutes, and the day of the week
    const hoursSpan = document.createElement("span");
    const minutesSpan = document.createElement("span");
    const dayOfWeekSpan = document.createElement("span");

    // Добавляем элементы в контейнер с разделителями ":" и ", "
    // Adding elements to the container with separators ":" and ", "
    timeElement.append(hoursSpan, ":", minutesSpan, ", ", dayOfWeekSpan);

    // Создаём стили и добавляем их в head документа
    // Creating styles and adding them to the document head
    const style = createStyle();
    document.head.appendChild(style);

    return {
      element: timeElement,
      hours: hoursSpan,
      minutes: minutesSpan,
      dayOfWeek: dayOfWeekSpan,
    };
  }

  // Функция создаёт и возвращает стили для отображения времени
  // Function creates and returns styles for the time display
  function createStyle() {
    const style = document.createElement("style");
    style.textContent = `
      .time-display {
        position: fixed; /* Фиксированное положение на экране (не прокручивается) / Fixed position on the screen (does not scroll) */
        bottom: 10px; /* Отступ от нижнего края экрана / Distance from the bottom edge of the screen */
        left: 250px; /* Отступ от левого края экрана / Distance from the left edge of the screen */
        padding: 8px; /* Внутренний отступ (пространство вокруг текста) / Inner padding (space around the text) */
        font-size: 24px; /* Размер шрифта / Font size */
        font-weight: bold; /* Жирный шрифт / Bold font */
        z-index: 1000; /* Приоритет слоя (чтобы не перекрывался другими элементами) / Layer priority (to stay above other elements) */
        color: black; /* Основной цвет текста / Main text color */
        text-shadow: 1px 1px 2px white; /* Тень текста для лучшей читаемости / Text shadow for better readability */
        background: rgba(255, 255, 255, 0.4); /* Полупрозрачный белый фон / Semi-transparent white background */
        border-radius: 5px; /* Скруглённые углы блока / Rounded block corners */
      }

      .time-display span {
        transition: color 1s ease; /* Плавная смена цвета текста в течение 1 секунды / Smooth text color transition over 1 second */
      }
    `;
    return style;
  }

  // Функция обновляет отображаемое время
  // Function updates the displayed time
  function updateDisplayTime(display) {
    const now = new Date();

    // Получаем текущие часы и минуты, дополняем нулями до двух знаков
    // Getting current hours and minutes, padding to two digits
    const hours = now.getHours().toString().padStart(2, "0");
    const minutes = now.getMinutes().toString().padStart(2, "0");

    // Получаем день недели в коротком формате (например, "пн", "вт")
    // Getting the day of the week in short format (e.g., "Mon", "Tue")
    const dayOfWeek = new Intl.DateTimeFormat("ru-RU", { weekday: "short" }).format(now);

    // Генерируем случайный цвет
    // Generating a random color
    const color = getRandomColor();

    // Обновляем текстовое содержимое элементов
    // Updating the text content of elements
    display.hours.textContent = hours;
    display.minutes.textContent = minutes;
    display.dayOfWeek.textContent = dayOfWeek;

    // Меняем цвет текста
    // Changing text color
    display.hours.style.color = color;
    display.minutes.style.color = color;
  }

  // Функция генерирует случайный цвет с ограниченной яркостью
  // Function generates a random color with limited brightness
  function getRandomColor() {
    const r = Math.floor(Math.random() * 200);
    const g = Math.floor(Math.random() * 200);
    const b = Math.floor(Math.random() * 200);
    return `rgb(${r}, ${g}, ${b})`;
  }

  // Основная функция инициализации
  // Main initialization function
  function init() {
    const display = createTimeDisplay(); // Создаём элемент отображения / Creating display element
    document.body.appendChild(display.element); // Добавляем его в body / Adding it to the body
    updateDisplayTime(display); // Первоначальное обновление / Initial update
    setInterval(() => updateDisplayTime(display), 3000); // Обновляем каждую 3 секунды / Updating every 3 seconds
  }

  init(); // Запускаем скрипт / Running the script
})();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址