Js add css style file

How to include CSS inside a JavaScript file

I’m a newbie to HTML, CSS and JS. Currently I’m working on JavaScript to create a pie chart. My doubt is how can I include a CSS hover function within a function. Can anyone help me include CSS hover inside a function in the JavaScript code below?

  

I’m guessing you’re looking for something like document.getElementById(‘element_id’).onMouseOver(some function)

Источник

Распространенные способы подключения CSS в JavaScript-приложения

Каждый способ подключения CSS в приложениях React, Vue или Angular имеет свои преимущества и недостатки . Рассмотрим каждый из них более подробно.

Доступные варианты подключения

Рассмотрим некоторые из наиболее часто используемых методов подключения CSS в JavaScript.

Вариант 1: таблица стилей

Мы начнем с привычного подхода – ссылка на один общий файл CSS.

Но по мере того, как приложение становится больше и сложнее, поддерживать единую таблицу стилей будет все труднее. Sass и PostCSS помогут справиться с подобными проблемами.

В зависимости от сложности приложения этот файл CCS будет загружаться асинхронно и блокировать рендеринг остальной части приложения. Поэтому данный метод для небольших приложений.

Тем не менее, общая таблица стилей обеспечивает четкое разделение между бизнес-логикой и стилями приложения. Кроме этого отдельный файл CSS легко кэшируется браузерами.

Вариант 2: Модули CSS

Стили с областями видимости позволяют программно генерировать имена классов, специфичные для конкретного компонента. Область действия CSS определяется конкретным компонентом. Это гарантирует, что имена используемых классов будут уникальными.

Подобная автоматизация приводит к появлению автоматически сгенерированных имен классов, таких как header__2lexd. Часть в конце имени — это хешированный селектор, который является уникальным.

Модули CSS предлагают различные способы управления сгенерированными именами классов. Более подробно об этом можно узнать из документации по модулям .

Представьте, что вы хотите использовать глобальный класс .screen-reader-text, который можно применить к любому компоненту приложения. При использовании CSS-модулей вам придется обратиться к псевдоселектору :global, который определяет размещенные внутри него стили как глобально доступные.

Пока вы импортируете файл CSS, который включает в себя блок объявления :global, в таблицу стилей компонента, вы будете использовать этот глобальный селектор.

Читайте также:  Kotlin spring boot security

Вот пример псевдоселектора :global в действии.

// typography.css :global < .aligncenter < text-align: center; >.alignright < text-align: right; >.alignleft < text-align: left; >>

А с помощью таких инструментов, как PostCSS Nested или Sass, вы можете импортировать шаблоны непосредственно в селектор.

Также обратите внимание на то, как мы ссылаемся на имена классов в узлах DOM. Нужно, чтобы имена отдельных документов для Vue , React и Angular говорили сами за себя. Вот небольшой пример того, как ссылки на классы используются в компоненте React.

// ./css/Button.css .btn < background-color: blanchedalmond; font-size: 1.4rem; padding: 1rem 2rem; text-transform: uppercase; transition: background-color ease 300ms, border-color ease 300ms; &:hover < background-color: #000; color: #fff; >> // ./Button.js import styles from "./css/Button.css"; const Button = () => (  ); export default Button;

Модули CSS позволяют воспользоваться преимуществами стилей с заданной областью видимости без ущерба для производительности приложения.

Также модули CSS можно комбинировать с препроцессорами. Sass, Less, PostCSS могут быть интегрированы в процесс сборки с использованием модулей CSS.

Вариант 3: CSS in JS

Есть несколько пакетов, которые делают создание кода CSS-in-JS максимально безболезненным. JSS , Emotion и Styled Components — это лишь некоторые из них.

CSS-in-JS работает следующим образом. Вы пишете CSS-код, связанный с отдельным компонентом. Во время компиляции приложения используемая платформа выводит CSS-код только тех компонентов, которые постоянно отображаются на веб-странице.

Фреймворки CSS-in-JS выводят связанный CSS-код в теге раздела . Это позволяет оперативно загружать критический CSS. При этом стили имеют ограниченную область действия, а имена классов хэшируются.

При навигации пользователя по приложению стили невостребованных компонентов будут удалены из раздела . На их место будут добавлены стили входящих компонентов. Это повышает производительность приложения, позволяет обойтись без HTTP- запроса и не блокирует рендеринг. Также CSS-in-JS позволяет ссылаться на состояния компонентов и функции для рендеринга стилей CSS.

Основные аспекты использования данного подхода:

  • Некоторые решения CSS-in-JS требуют, чтобы стили были встроены в элемент, который вы пытаетесь стилизовать. Для этого используется очень сложный синтаксис.
  • CSS-in-JS предоставляет мощные инструменты, которые сложно реализовать с помощью модулей CSS или простой таблицы стилей.
  • Нужно уметь использовать новейшие функции CSS, такие как вложенность и переменные.

Пример компонента React с использованием библиотеки Styled Components:

// ./Button.js import styled from 'styled-components'; const StyledButton= styled.button` background-color: blanchedalmond; font-size: 1.4rem; padding: 1rem 2rem; text-transform: uppercase; transition: background-color ease 300ms, border-color ease 300ms; &:hover < background-color: #000; color: #fff; >`; const Button = () => ( Click Me! ); export default Button;

Заключение

Есть несколько различных способов, позволяющих справиться с CSS-архитектурой в приложениях JavaScript. Но у каждого из них есть свои достоинства и свои недостатки.

Источник

How to load CSS files using JavaScript?

Sometimes, the task is change the page themes and to use different CSS files on the same page content. In such tasks the need is to fetch a CSS and load it dynamically while selecting a theme. In this case the CSS file has to be accessed, loaded and even selected through a javascript program. Using HTML and javascript code this process of loading the CSS file is demonstrated in this article. This is shown by using two different examples. In the first example, a CSS file is selected on the windows load event. In the second example, two buttons are used to load separate CSS files on button clicks.

Example 1: Loading the CSS file on window.onload( )

Folder and Pages Design Steps

  • Step 1 − Make an html file and start writing the code. Create a CSS file and define the styles for background, p tag and h1 tag.
  • Step 2 − Inside the tags in the html file, write the code which will be executed when the page is fully loaded. Use window.onload() for this.
  • Step 3 − Inside the tags write the code to fetch the head tag first. Then make a link tag and set its properties.
  • Step 4 − Select the css file and add it to the href of the link.
  • Step 5 − Now add this created link into the head tag.
  • Step 6 − Load the HTML file in a browser and check the result.

Main html file : loadcss1.html

CSS file used: cssfilenew.css

Code For loadcss1.html

      

Example 1

To load the CSS file using JS

Code For cssfilenew.css

Viewing The Result

For seeing the result open the html file in a browser. The styles will be included in the CSS file that is loaded using Javascript.

Example2: Loading the different CSS files on click of two buttons

Folder and Pages Design Steps

Step 1 − Make an HTML file and start writing the code. Create two CSS files and define the different styles for the background, p tag, and h1 tag in these.

Step 2 − Inside the tags in the HTML file, make two functions, function1, and function2. Write the code for these functions which will be executed when these functions will be called.

Step 3 − Inside the tags, in both of these functions write the code to fetch the head tag first. Then make a link tag and set its properties.

Step 4 − Select the different CSS files through both functions and add these to the href of the link.

Step 5 − Add this created link to the head tag.

Step 6 − Now create two buttons and call these two functions on different button clicks.

Step 7 − Load the HTML file in a browser. The CSS file is not added initially. It will be added on the button clicks. Click both buttons and check the results.

Main HTML file: loadcss2.html

CSS files used: cssfile.css and cssfilenew.css

Code For loadcss2.html:

      

Example 1

To load the CSS file using JS

Code For cssfile.css

Code For cssfilenew.css

Viewing The Result

For seeing the result open the html file in a browser. The styles will be included from the CSS files that are loaded on button clicks.

3In this article, using two different examples, the ways to show how to load the CSS file dynamically using the javascript code are given. First, the method is given where a CSS file is selected when the page is loaded and then the way of using the CSS files on button click is given. For this two buttons are clicked to load different CSS files and change the style of the same page.

Источник

Javascript Set CSS Set CSS styles with javascript

2. Global styles

 var style = document.createElement('style'); style.innerHTML = ` #target < color: blueviolet; >`; document.head.appendChild(style); 

global styles

3. CSSOM insertRule

 var style = document.createElement('style'); document.head.appendChild(style); style.sheet.insertRule('#target '); 

insertRule

While it might look similar to the 2nd option, it’s definitely different.
As you can see in Chrome devtools, tag is empty, but the style (darkseagreen color) is applied to the element. Also the color can’t be changed via devtools because Chrome doesn’t allow editing dynamic CSS styles. Actually such behavior was the motivation to write this post. A popular CSS-in-JS library Styled Components use this feature to inject styles in production mode because of performance. This feature might be undesirable in specific projects or environments and some folks complain about it in the project’s issues.

4. Constructable Stylesheets (July 2019 update)

// Create our shared stylesheet: const sheet = new CSSStyleSheet(); sheet.replaceSync('#target '); // Apply the stylesheet to a document: document.adoptedStyleSheets = [sheet]; 

More details are here.
This option is only valid for Chrome, so use with caution. Do you know other options to add styles with javascript? What is your preferred option these days? Thanks for reading!

Источник

Оцените статью