Некодим логотипНекодим
МодификацииПубликацииНекодИИмЦены
Некодим логотипНекодим

© 2020-2026 Некодим

Готовые модификации для вашего сайта. Улучшайте функциональность и дизайн без программирования.

Компания

  • Контакты
  • Публичная оферта
  • Политика конфиденциальности
  • Согласие на обработку данных
  • Лицензионное соглашение
  • Реферальная программа

Полезное

  • Модификации
  • Публикации
  • Каталог блоков Tilda
  • MCP для агентов
  • Журнал изменений
  • Доска почёта

Личный кабинет

  • Вход
  • Регистрация
  • Цены
Журнал измененийИстория GitФайлыTilda MCP
Каталог файлов

tilda-autoscale-1.0.js

Код файла
Версия от 03.10.2026, 07:00:58 МСК
Оригинал на CDNСнимок 56c3b845Полный текст
101	 * больше фактической ширины экрана с вычетом ширины скроллбара.102	 * Поэтому при расчете брейкпоинта, ориентируемся на window.innerWidth.103	 * Так же зум-значение может быть меньше 1 при наличии вертикального скроллбара,104	 * когда фактическая ширина экрана равна, например, 1190, а брейкпоинт 1200.105	 *106	 * @param {boolean} isWindowsOS107	 * @returns {number}108	 */109	function getZoomValue(isWindowsOS) {110		const leftOffset = (allRecords && parseInt(getComputedStyle(allRecords).paddingLeft, 10)) || 0;111		const rightOffset = getRightOffset();
История файла и сравнение версий
  • 03.10.2026, 07:00:58 · 56c3b845
112
const offsetX = leftOffset + rightOffset;
113 const hasScrollbar = Math.abs(window.innerWidth - document.documentElement.clientWidth) > 1 || rightOffset > 0;
114 const windowFullWidth = window.innerWidth - offsetX;
115 const windowWidth = document.documentElement.clientWidth - offsetX;
116 const gridWidth = breakpoints.find(breakpoint => windowFullWidth > breakpoint);
117 if (!gridWidth) return 1;
118 const zoomValue = Math.round((windowWidth / gridWidth) * 100000) / 100000;
119 const processedZoomValue = (hasScrollbar ? zoomValue : Math.max(zoomValue, 1)) || 1;
120 const decimal = isWindowsOS ? 2 : 5;
121 return getTruncatedValue(processedZoomValue, decimal);
122 }
123
124 /**
125 * При открытии попапа нужно учесть отступ, который задаётся для body справа
126 * @returns {number}
127 */
128 function getRightOffset() {
129 if (!document.body.classList.contains('t-body_popupshowed')) return 0;
130 return parseInt(getComputedStyle(document.body).paddingRight, 10) || 0;
131 }
132
133 /**
134 * Для Windows обрезаем значение до 2-х знаков после запятой, чтобы избежать проблем с рендерингом
135 * @param {number} value
136 * @param {number} decimal
137 * @returns {number}
138 */
139 function getTruncatedValue(value, decimal) {
140 if (!value) return 1;
141 return Math.floor(value * Math.pow(10, decimal)) / Math.pow(10, decimal);
142 }
143}
144
145function t_autoscale__setGeneralStyles() {
146 const styleId = 'tilda-autoscale-main-style';
147 if (document.getElementById(styleId)) return;
148 const { scaledRecordSelector, variableName, breakpoints } = t_autoscale__getAutoscaleData();
149
150 const style = document.createElement('style');
151 style.textContent = breakpoints
152 .slice()
153 .reverse()
154 .map(gridWidth => {
155 return `@media (min-width: ${gridWidth}px) {
156 ${scaledRecordSelector} {
157 max-width: ${gridWidth}px;
158 }
159 }`;
160 })
161 .join(' ');
162
163 style.textContent += `@media (min-width: ${Math.min(...breakpoints)}px) {
164 ${scaledRecordSelector} {
165 zoom: var(${variableName}, 1);
166 }
167 }`;
168
169 style.id = styleId;
170 document.head.appendChild(style);
171}
172
173/**
174 * Для динамической высоты, заданной в vh, необходимо сохранять значение, которое задаёт пользователь,
175 * поэтому уменьшаем его на зум-значение, чтобы 100vh соответствовали 100% высоты экрана.
176 */
177function t_autoscale__processDynamicHeight() {
178 const { scaledRecordSelector, dynamicHeightAttribute, variableName } = t_autoscale__getAutoscaleData();
179 const allDynamicHeightElements = document.querySelectorAll(`${scaledRecordSelector} [${dynamicHeightAttribute}]`);
180 allDynamicHeightElements.forEach(element => {
181 if (element.classList.contains('t-map')) return;
182 const currentHeight = element.getAttribute(dynamicHeightAttribute);
183 if (!currentHeight) return;
184 const currentProperty = getCurrentProperty(element);
185 element.style.setProperty(currentProperty, `calc(${currentHeight}vh / var(${variableName}, 1))`);
186 });
187
188 function getCurrentProperty(element) {
189 if (element.style.getPropertyValue('--height') && element.style.getPropertyValue('--height').includes('vh')) {
190 return '--height';
191 }
192 if (element.style.minHeight && element.style.minHeight.includes('vh')) return 'min-height';
193 if (element.style.maxHeight && element.style.maxHeight.includes('vh')) return 'max-height';
194 return 'height';
195 }
196}
197
198/**
199 * Некоторые элементы при наличии свойства zoom некорректно масштабируются, поэтому для них зум будет сброшен
200 */
Предыдущие 100 строкСледующие 100 строк