Learn Jquery Css Method

How to change CSS Property using jQuery

To get and set/change css property using jQuery; In this tutorial, you will learn how to change CSS properties like background color, font size, styling, font color etc, of html elements using jQuery css() method.

How to change CSS Property using jQuery

Using the jQuery CSS () method is used to get or set the style/css properties ​​for the selected elements.

Syntax of jQuery css() method

This can use to get css property of element.

$(selector).css("propertyname","value");

This can use to set css property of element.

It can use to set multiple css properties of elements.

Читайте также:  Экспоненциальная форма числа python

Example 1 – To get css property of html element using jQuery css()

It can use to get the value of a specified CSS property.

      

The background-color of this paragraph is red.

The background-color of this paragraph is green.

The background-color of this paragraph is blue.

Example 2 – To get all matched css property of html element using jQuery css()

This property is used to determine a specific value for all matching elements.

      

The background-color of this paragraph is red.

The background-color of this paragraph is green.

The background-color of this paragraph is blue.

This paragraph has no background-color.

In the above example, you can see that, set the all matched property background color using css() method.

Example 3 – To set/change all css property of html element using jQuery css()

This method gives you the convenience of adding multiple property values ​​together.

      

The background-color of this paragraph is red.

The background-color of this paragraph is green.

The background-color of this paragraph is blue.

In the above example 3 , you can see that, set the all matched mutlitple property background color, font-size using css() method.

Источник

Получение и установка 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 :

Источник

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.

Источник

How to change CSS using jQuery?

Since we all know that we can perform many fun tasks using jQuery due to its lightweight and “write less, do more” agenda. One such task is rendering changes to CSS style properties of HTML elements. You can change CSS by using the css() method of jQuery.

Here in this guide, we have explained this method in detail, moreover, we have demonstrated different examples that help you better understand the method and its usage.

css() Method

The css() method in jQuery is used for the purpose of either fetching or applying one or more style properties to an HTML element.

To apply multiple CSS properties.

To better understand the css() method, let’s explore some examples.

Example 1: How to set a CSS property

Suppose you want to set the background color of a element using the css() method in jQuery.

In the above HTML code, we have created an , and a element.

$ ( document ) .ready ( function ( ) {

$ ( «h1» ) .css ( «background-color» , «yellow» ) ;

In the above jQuery code, we have applied a yellow background color to the element using the css() method.

Before clicking the button.

After clicking the button.

The background color of the heading has been set successfully.

How to fetch a CSS property

Suppose you want to fetch any CSS property of an element, for instance, background color of a div element. Follow the code below.

< br > < button >Return background — color of div

Here we have created a , and a element.

$ ( document ) .ready ( function ( ) {

alert ( «Background color = » + $ ( «div» ) .css ( «background-color» ) ) ;

In the above code, the css() method is used only to extract the background color assigned to the element. Moreover, an alert message has been created that will display the background color of the div.

The background color of the div element has been fetched and displayed successfully.

How to set multiple CSS properties

Suppose you want to assign multiple style properties to any HTML element all at once. Follow the example below.

In the above code, we have created a

element along with a element.

$ ( document ) .ready ( function ( ) {

$ ( «p» ) .css ( { «background-color» : «yellow» , «padding» : «25px» , «width» : «200px» } ) ;

Using the jQuery css() method we have applied a background color to the

element and assigned it some padding and width.

It can be verified from the above output that multiple styles are applied to the paragraph all at once.

Conclusion

You can change CSS using the jQuery css() method which is used for the purpose of getting or setting style properties of an element. Using this method you can apply multiple styles to an HTML all at once by manipulating CSS style properties. This tutorial guides you on how to change CSS in various ways through jQuery css() method along with the relevant examples for better understanding.

About the author

Naima Aftab

I am a software engineering professional with a profound interest in writing. I am pursuing technical writing as my full-time career and sharing my knowledge through my words.

Источник

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