How to apply CSS style using jQuery?

jQuery — Get and Set CSS Classes

With jQuery, it is easy to manipulate the style of elements.

jQuery Manipulating CSS

jQuery has several methods for CSS manipulation. We will look at the following methods:

  • addClass() — Adds one or more classes to the selected elements
  • removeClass() — Removes one or more classes from the selected elements
  • toggleClass() — Toggles between adding/removing classes from the selected elements
  • css() — Sets or returns the style attribute

Example Stylesheet

The following stylesheet will be used for all the examples on this page:

.important <
font-weight: bold;
font-size: xx-large;
>

jQuery addClass() Method

The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:

Example

You can also specify multiple classes within the addClass() method:

Example

jQuery removeClass() Method

The following example shows how to remove a specific class attribute from different elements:

Читайте также:  Use byte in java

Example

jQuery toggleClass() Method

The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:

Example

jQuery css() Method

The jQuery css() method will be explained in the next chapter.

jQuery Exercises

jQuery CSS Reference

For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

jQuery — css() Method

The css() method sets or returns one or more style properties for the selected elements.

Return a CSS Property

To return the value of a specified CSS property, use the following syntax:

The following example will return the background-color value of the FIRST matched element:

Example

Set a CSS Property

To set a specified CSS property, use the following syntax:

The following example will set the background-color value for ALL matched elements:

Example

Set Multiple CSS Properties

To set multiple CSS properties, use the following syntax:

The following example will set a background-color and a font-size for ALL matched elements:

Example

jQuery Exercises

jQuery CSS Reference

For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Получение и установка CSS-свойств элементам в jQuery

jQuery - Работа со стилями элемента

В jQuery работа со стилями HTML элементов осуществляется через метод css . Данный метод используется как получения значения стилей, так и для их добавления, изменения и удаления.

Как получить стиль элемента в jQuery

Первый вариант метода css — это получение окончательного значения CSS-свойства непосредственно применяемого к элементу.

// Вариант 1 (получение окончательного одного CSS свойства) .css( propertyName ) // propertyName (тип: Строка) – имя CSS-свойства, значение которого нужно получить .css( propertyNames ) // propertyName (тип: Массив) – массив, состоящий из одного или нескольких CSS-свойств, значения которых нужно получить

Данный метод, если его применить к набору элементов, возвращает значение CSS свойства только для первого его элемента.

Пример, в котором получим цвет фона непосредственно применённого к элементу #header :

var bgHeader = $('#header').css('background-color');

В jQuery названия CSS-свойств можно указывать как в CSS, так и как это принято в JavaScript. Т.е. убирать дефисы и заменять буквы, следующие за каждым дефисом на прописные.

// можно и так var bgHeader = $('#header').css('backgroundColor');

Если необходимо получить значения указанного CSS свойства или набора этих свойств у всех элементов текущего набора, то в этом случае необходимо использовать, например, метод each.

Например, определим значение свойства display у всех выбранных элементов и выведем их в консоль:

// переберём все элементы .container $('.container').each(function(index){ // значение css-свойства display текущего элемента набора var display = $(this).css('display'); // выведем результат в консоль (индекс элемента в наборе и его значение css-свойства display) console.log(index + '. display = '+ display); });

Кроме этого, метод css позволяет также получить сразу несколько CSS свойств у элемента.

Например, при нажатии на HTML элемент div выведим его ширину и высоту:

 .  

Как изменить или добавить стиль к элементу в jQuery

Установить стиль элементу осуществляется тоже с помощью метода css, но в этом случае используется следующий синтаксис:

// 1 вариант (для установки одного стиля элементу) .css( propertyName, value ) // 2 вариант (установка значения стиля с помощью функции) css( propertyName, function ) // 3 вариант (для установки несколько стилей элементу) css( properties ) // Описание параметров: // propertyName (тип: String) – имя CSS-свойства // value (тип: String или Number) – значение, которое нужно установить CSS-свойству // function – функция, результат выполнения которой будет установлен в качестве значения CSS-свойству // Синтаксис функции: // Function( Integer index, String value ) => String или Number // В качестве аргументов функция получает индекс элемента (index) и текущее окончательное значение CSS-свойства (value) // properties (тип: объект JavaScript, содержащий ноль или более пар ключ-значение) – объект, состоящий из пар DOM-свойство-значение, которые нужно установить элементу.

При установлении стилей с помощью метода css , они задаются ко всем элементам текущего набора.

Например, добавим ко всем элементам .info серый цвет фона (background):

Если необходимо применить к каждому элементу текущего набора сразу несколько CSS свойств, то в качестве параметра этого метода необходимо использовать объект JavaScript, содержащий пары ‘имяСвойства’ : значение.

.css({'имяСвойства1':значение, 'имяСвойства2':значение. })

Пример, в котором показано как можно задать несколько CSS-свойств к элементам .success :

$('.success').css({ 'color':'green', 'font-size':'16px' });

В качестве значения строки также можно использовать относительные значения, которые начинаются с += или -= . Первое выражение используется для увеличения текущего значения CSS свойства, а второе — для уменьшения.

Например, увеличим отступ слева и справа у элементов .container на 10px :

$('.container').css({ "padding-left": "+=10", "padding-right":"+=10" });

Ещё один способ использования метода css — это применение в качестве 2 параметра функции.

.css('имяСвойства',функция) // функция: Function( Integer index, String value ) => String или Number

Вариант использования метода css, у которого в качестве второго параметра используется функция обычно находить применение, когда значение необходимо как-то вычислить или определить по какому-то алгоритму.

Например, установим всем элементам .text , у которых цвет шрифта не равен чёрному, CSS свойство color , равное red .

$('.text').css('color',function(index,value){ if (value!=='rgb(0, 0, 0)') { return 'red'; } });

Например, поменяем значение CSS свойства width у всех элементов img на странице, находящихся #content :

Как удалить определённый стиль у элемента

Для того чтобы в jQuery убрать определённый стиль у элемента, ему необходимо присвоить просто пустую строку.

Например, уберём у всех изображений на странице CSS свойство height :

Источник

How to apply CSS style using jQuery?

We can use jquery’s .css() method to apply CSS style on the given webpage. jQuery is a javascript library that helps us manipulate the DOM easily and efficiently using its various helper methods and properties. It allows us to add interactivity to the DOM as well as add and change the CSS styles of the DOM elements.

Syntax

$(selector).css(property, value)

JQuery css() method accepts either an argument of type object, with key as the CSS property name and value as the desired property value to be set to, or just a pair of comma-separated CSS property name and value.

Let’s understand how to use the css() method, by jQuery, to apply styles to the HTML elements with the help of some suitable examples.

Example 1

In this example, we will change the text color of the “p” tag after clicking the button using css() jQuery method.

      

This is p tag content!

Example 2

In this example, we will change the font color and background color of the “p” tag after clicking the button using css() method provided by jQuery.

      

This is p tag content!

Conclusion

In this article, we learned about the css() method provided by jQuery, and we used it to apply the CSS style properties to the DOM elements, with the help of 2 examples, In the first example, we changed the “text-color” of the content on a button click, and in the second example, we changed the “text-color” and “background-color” of the content on the click of a button.

Источник

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