Цель < /h1>
Я получаю прогноз погоды от NWS, который имеет очень специфический форматирование HTML, который я хочу сохранить. Прогноз всегда изменится как по своей длине, так и по ширине. Я хочу масштабировать размер шрифта текста до всегда на экране мобильного телефона, даже если текст действительно мал, а длина каждой строки должна быть сохранена. Форматирование текста никогда не должно меняться (например, строки никогда не должны обертываться).
Как должен выглядеть вывод
/> Мое текущее решение-это использование SVG, но я не совсем получаю форматирование, которое я ищу.function getFireWeatherForecast() {
/* Sample API response */
return "Fire Weather Discussion
FNUS56 KMFR 252130
FWFMFRFire Weather Forecast for southern Oregon and northern California
National Weather Service Medford, OR
230 PM PDT Fri Jul 25 2025...RED FLAG WARNING REMAINS IN EFFECT UNTIL 11 PM PDT THIS
EVENING FOR ABUNDANT LIGHTNING ON DRY FUELS FOR FIRE WEATHER
ZONES 280, 281, 282, 284, 285, 624, AND 625....DISCUSSION...Another episode of scattered to numerous
thunderstorms is expected this evening, focused upon northern
California with activity extending into south central Oregon.
Storms will be slow-moving and produce rain, but the amount of
lightning is expected to exceed critical thresholds. Isolated
late day storms are possible for portions of the area Saturday
through Monday. The next trough may bring an enhanced risk of
thunderstorms during mid-week.
Fire Weather Forecast for CAZ282CAZ282-CAZ282-261215-
Shasta-Trinity National Forest in Siskiyou County-
230 PM PDT Fri Jul 25 2025...RED FLAG WARNING IN EFFECT UNTIL 11 PM PDT THIS EVENING....Tonight...
* Sky/weather...........Mostly cloudy with scattered showers and
thunderstorms until midnight, then partly cloudy. Haze after
midnight.
* Min temperature.......45-55.
* Max humidity..........85-100 percent valleys and 65-80 percent
ridges.
* 20-foot winds.........
* Valleys/lwr slopes...Southeast winds 5 to 10 mph. Gusts up to 25
mph in the evening.
* Ridges/upr slopes....Southeast winds 6 to 10 mph with gusts to
around 25 mph shifting to the southwest 5 to 6 mph after
midnight.
* Mixing Height.....................4000-7200 ft AGL until 2100,
then 100-1600 ft AGL.
* Chance of lightning...............44 percent.
* Chance of wetting rain (.10 in)...30 percent.
* Chance of wetting rain (.25 in)...17 percent. &&
TEMP / HUM / POP
Mount Shasta 51 92 40
.EXTENDED...
.SUNDAY NIGHT...Mostly clear. Lows 45 to 55. West winds 5 to
8 mph.
.MONDAY...Mostly clear. Highs 75 to 85. Light winds becoming
southwest 5 to 6 mph in the afternoon and evening.";
}
function createForecastSVG(forecast) {
const SVG_NS = "http://www.w3.org/2000/svg";
const XHTML_NS = "http://www.w3.org/1999/xhtml";
// 1. SVG shell
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
// 2. foreignObject
const foreignObject = document.createElementNS(SVG_NS, "foreignObject");
svg.appendChild(foreignObject);
// 3. XHTML that actually holds the text
const div = document.createElementNS(XHTML_NS, "div");
div.innerHTML = forecast;
foreignObject.appendChild(div);
// 4. Measure content size once the browser has rendered a frame
requestAnimationFrame(() => {
const forecastWidth = div.scrollWidth;
const forecastHeight = div.clientHeight;
foreignObject.setAttribute("width", `${forecastWidth}px`);
foreignObject.setAttribute("height", `${forecastHeight}px`);
svg.setAttribute(
"viewBox",
`0 0 ${forecastWidth} ${forecastHeight}`
);
});
return svg;
}
document.getElementById("forecastForm").addEventListener("submit", async (formSubmitEvent) => {
formSubmitEvent.preventDefault();
const fireWeatherForecast = getFireWeatherForecast();
// Write the output text to the page
let forecastWrapper = document.getElementById("forecast-card");
forecastWrapper.innerHTML = ""; // clear previous forecast
const svg = createForecastSVG(fireWeatherForecast);
forecastWrapper.appendChild(svg);
forecastWrapper.style.visibility = "visible";
});< /code>
#forecast-card {
/* Positioning inner content styles */
visibility: hidden;
display: block;
overflow-x: scroll;
overflow-y: scroll;
/* Styling for the look of the card */
margin: 2rem auto 0 auto;
background: rgba(30, 32, 35, 0.8);
padding: 1.5rem;
/* HTML content related styles */
font-family: monospace;
font-size: 0.5rem;
color: #e1e1e1;
white-space: pre; /* Preserve exact formatting */
}
.forecast-card svg {
max-width: 100%;
display: inline-block;
}< /code>
Submit
< /code>
< /div>
< /div>
< /p>
текущие проблемы < /h1>
Lines wrap < /li>
Высота карты не соответствует высоте текста (высота карты дольше) < /li>
< /ul.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... -using-svg
Как масштабировать всегда изменяющий текст HTML, чтобы соответствовать мобильному экрану с помощью SVG ⇐ Javascript
Форум по Javascript
1753501244
Anonymous
Цель < /h1>
Я получаю прогноз погоды от NWS, который имеет очень специфический форматирование HTML, который я хочу сохранить. Прогноз всегда изменится как по своей длине, так и по ширине. Я хочу масштабировать размер шрифта текста до [b] всегда [/b] на экране мобильного телефона, даже если текст действительно мал, а длина каждой строки должна быть сохранена. Форматирование текста никогда не должно меняться (например, строки никогда не должны обертываться).
Как должен выглядеть вывод
/> Мое текущее решение-это использование SVG, но я не совсем получаю форматирование, которое я ищу.function getFireWeatherForecast() {
/* Sample API response */
return "Fire Weather Discussion
FNUS56 KMFR 252130
FWFMFRFire Weather Forecast for southern Oregon and northern California
National Weather Service Medford, OR
230 PM PDT Fri Jul 25 2025...RED FLAG WARNING REMAINS IN EFFECT UNTIL 11 PM PDT THIS
EVENING FOR ABUNDANT LIGHTNING ON DRY FUELS FOR FIRE WEATHER
ZONES 280, 281, 282, 284, 285, 624, AND 625....DISCUSSION...Another episode of scattered to numerous
thunderstorms is expected this evening, focused upon northern
California with activity extending into south central Oregon.
Storms will be slow-moving and produce rain, but the amount of
lightning is expected to exceed critical thresholds. Isolated
late day storms are possible for portions of the area Saturday
through Monday. The next trough may bring an enhanced risk of
thunderstorms during mid-week.
Fire Weather Forecast for CAZ282CAZ282-CAZ282-261215-
Shasta-Trinity National Forest in Siskiyou County-
230 PM PDT Fri Jul 25 2025...RED FLAG WARNING IN EFFECT UNTIL 11 PM PDT THIS EVENING....Tonight...
* Sky/weather...........Mostly cloudy with scattered showers and
thunderstorms until midnight, then partly cloudy. Haze after
midnight.
* Min temperature.......45-55.
* Max humidity..........85-100 percent valleys and 65-80 percent
ridges.
* 20-foot winds.........
* Valleys/lwr slopes...Southeast winds 5 to 10 mph. Gusts up to 25
mph in the evening.
* Ridges/upr slopes....Southeast winds 6 to 10 mph with gusts to
around 25 mph shifting to the southwest 5 to 6 mph after
midnight.
* Mixing Height.....................4000-7200 ft AGL until 2100,
then 100-1600 ft AGL.
* Chance of lightning...............44 percent.
* Chance of wetting rain (.10 in)...30 percent.
* Chance of wetting rain (.25 in)...17 percent. &&
TEMP / HUM / POP
Mount Shasta 51 92 40
.EXTENDED...
.SUNDAY NIGHT...Mostly clear. Lows 45 to 55. West winds 5 to
8 mph.
.MONDAY...Mostly clear. Highs 75 to 85. Light winds becoming
southwest 5 to 6 mph in the afternoon and evening.";
}
function createForecastSVG(forecast) {
const SVG_NS = "http://www.w3.org/2000/svg";
const XHTML_NS = "http://www.w3.org/1999/xhtml";
// 1. SVG shell
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("preserveAspectRatio", "xMinYMin meet");
// 2. foreignObject
const foreignObject = document.createElementNS(SVG_NS, "foreignObject");
svg.appendChild(foreignObject);
// 3. XHTML that actually holds the text
const div = document.createElementNS(XHTML_NS, "div");
div.innerHTML = forecast;
foreignObject.appendChild(div);
// 4. Measure content size once the browser has rendered a frame
requestAnimationFrame(() => {
const forecastWidth = div.scrollWidth;
const forecastHeight = div.clientHeight;
foreignObject.setAttribute("width", `${forecastWidth}px`);
foreignObject.setAttribute("height", `${forecastHeight}px`);
svg.setAttribute(
"viewBox",
`0 0 ${forecastWidth} ${forecastHeight}`
);
});
return svg;
}
document.getElementById("forecastForm").addEventListener("submit", async (formSubmitEvent) => {
formSubmitEvent.preventDefault();
const fireWeatherForecast = getFireWeatherForecast();
// Write the output text to the page
let forecastWrapper = document.getElementById("forecast-card");
forecastWrapper.innerHTML = ""; // clear previous forecast
const svg = createForecastSVG(fireWeatherForecast);
forecastWrapper.appendChild(svg);
forecastWrapper.style.visibility = "visible";
});< /code>
#forecast-card {
/* Positioning inner content styles */
visibility: hidden;
display: block;
overflow-x: scroll;
overflow-y: scroll;
/* Styling for the look of the card */
margin: 2rem auto 0 auto;
background: rgba(30, 32, 35, 0.8);
padding: 1.5rem;
/* HTML content related styles */
font-family: monospace;
font-size: 0.5rem;
color: #e1e1e1;
white-space: pre; /* Preserve exact formatting */
}
.forecast-card svg {
max-width: 100%;
display: inline-block;
}< /code>
Submit
< /code>
< /div>
< /div>
< /p>
текущие проблемы < /h1>
Lines wrap < /li>
Высота карты не соответствует высоте текста (высота карты дольше) < /li>
< /ul.>
Подробнее здесь: [url]https://stackoverflow.com/questions/79715354/how-to-scale-always-changing-html-text-to-fit-on-mobile-screen-using-svg[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия