css demo

Работа с CSS

Возвращает или изменяет значения css-величин у выбранных элементов страницы. Функция имеет четыре варианта использования:

возвращает значение css-величины styleName у выбранного элемента. Если выбрано несколько элементов, то значение будет взято у первого.

группе css-величин styleName1, styleName2, . будут присвоены значения value1, value2, . , у всех выбранных элементов.

css-величине styleName будет присвоено значение, возвращенное пользовательской функцией. Функция вызывается отдельно, для каждого из выбранных элементов. При вызове, ей передаются следующие параметры: index — позиция элемента в наборе, value — текущее значение css-величины styleName у элемента.

$(«.topBlock»).css(«top») вернет смещение по вертикали у первого элемента с классом topBlock
$(«.topBlock»).css(«top», «5px») установит смещение по вертикали равным 5px у всех элементов с классом topBlock
$(«.topBlock»).css() установит смещения по вертикали и горизонтали равными 5px и 0px у всех элементов с классом topBlock

Замечание: важно отметить, что используя метод .css(styleName) вы получите значения css-величины только первого элемента из всех выбранных. Если вам нужны значения всех элементов, то следует использовать конструкции типа .map() или .each().

В действии

найдем среди списка планет родную землю и выделим ее зеленым цветом:

~lt~!DOCTYPE html~gt~ ~lt~html~gt~ ~lt~head~gt~ ~lt~script src="https://code.jquery.com/jquery-latest.js"~gt~~lt~/script~gt~ ~lt~style~gt~ #list < width:260px; >.item < width: 250px; height: 20px; float: left; margin: 1px; padding: 3px; background-color: #EEEEEE; list-style-type:none; >~lt~/style~gt~ ~lt~/head~gt~ ~lt~body~gt~ ~lt~ul ~gt~ ~lt~li ~gt~Меркурий~lt~/li ~gt~ ~lt~li ~gt~Венера~lt~/li ~gt~ ~lt~li ~gt~Земля~lt~/li ~gt~ ~lt~li ~gt~Марс~lt~/li ~gt~ ~lt~li ~gt~Юпитер~lt~/li ~gt~ ~lt~li ~gt~Сатрурн~lt~/li ~gt~ ~lt~li ~gt~Уран~lt~/li ~gt~ ~lt~li ~gt~Нептун~lt~/li ~gt~ ~lt~li ~gt~Плутон~lt~/li ~gt~ ~lt~/ul~gt~ ~lt~script~gt~ $("#list .item").css("background-color", function(i,val)< if($(this).text() == "Земля") return "#cceecc"; else return val; >); ~lt~/script~gt~ ~lt~/body~gt~ ~lt~/html~gt~

Ссылки

  • css значения
  • стили элементов
  • получить значение css-величин
  • изменить значение css-величин
  • установить значение css-величин
  • присвоить значение css-величинам
  • .css()
  • css()

От автора jquery.page2page.ru

Мини-игра про поход за продуктами во время карантина.

Твой уникальный шанс напинать короновирусу буквально.

Источник

Using jQuery to Assign ‘Top’ Property to Div Based on Its ‘Height’ in CSS

The solution to the problem of centering text vertically within a DIV and creating a dynamic footer after a main text DIV with absolute positioning can be achieved by trying Solution 3. In order to position the #pager element using margins, a certain unit must be used.

Читайте также:  Visual studio code html шаблон

CSS set div ‘top’ with jquery from div ‘height’

My template contains numerous absolute positioning elements, and my primary text division has a varying height. Consequently, I require a footer that can adjust its size dynamically and follow the text division.

An attempt was made to assign the height value of the text div to the top state of the footer div.

Regrettably, an error is thrown by Chrome Dev tools.

The method ‘top’ is not available for the object [object Object]. This issue is being caused by an anonymous function.

So any idea or help for my problem?

 $('#footer').css('top', $('#text').outerHeight() + 'px'); 

Is it feasible to increase the top value by a few pixels given that it functions smoothly?

To properly position the #footer div, it is necessary to set the ‘top’ CSS property rather than invoking .top() directly on the div.

$("#footer").css('top', $("#text").height() + "px"); 

Substitute .top with .offset() .

 $('#footer').style.css("top",$('#text').style.css("height")); 

Positioning div to top of viewport using jQuery, How does your HTML/CSS look like? Make it overlaying the viewport you can use position:absolute or position:fixed in combination with a high z-

JQuery CSS doesn’t work to set Top position

Kindly review the screenshot of Chrome console. The jQuery code’s first line is intended to adjust the «Top Position» of the «#footer» DIV to 1426px. However, jQuery(«#footer»).position().top displays it as 1401. It is anticipated to be 1426, but it is shown as 1401. Please advise if you comprehend the root causes.

The problem has been resolved by changing the «position» property of #footer element from «static» to «absolute». The issue arose because the «position» CSS property was undefined, resulting in the default static setting.

While .top provides only the numerical value, top requires a specific unit such as px , em , or % .

jQuery('#footer').css("top", jQuery('#pager').position().top + 40 + "px"); 
$top=jQuery('#pager').css('top'); if($top.match(/^-/g)) < $top= '-'+parseInt($top.replace(/\D/g,'')); >else < $top= parseInt($top.replace(/\D/g,'')); >$top=$top+40 jQuery('#footer').css("top", $top + "px"); 

When positioning the #pager element using margins, $top=jQuery(‘#pager’).css(‘margin-top’); must be utilized.

CSS left property, Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you

Setting CSS Top value using jquery not working

I am trying to vertically center the text within a DIV using percentage heights instead of fixed pixel heights.

 
Image Text

I possess numerous divs, wherein the «myText» content may vary from one line to three lines.

I’m utilizing jQuery to determine the height and adjust the TOP position accordingly.

The functionality is not effective as it always produces the same TOP value and fails to identify the height of «myText» when the text spans over 2 or 3 lines.

$('.myText').each(function(index,element) < var textHeight = $(element).height(); var vertAdj = ((imageHeight - textHeight) / 2); $(element).css('top', vertAdj); >); 

Refer to the .each reference documentation for further details, available at http://api.jquery.com/each/.

Читайте также:  Горизонтальная линия в HTML

JQuery animate. How to set top and left in auto, Use JS instead of jQuery to reset the CSS state when animation completed. Try this: $(

JQuery set top and left half of elements width and height

Here’s the fiddle for my project, which can be found at http://jsbin.com/ipEmIBAfa/3/edit.

My objective is straightforward. I obtain the height of my element, divide it by 2, and assign the resulting value to both the margin-top and margin-left css properties of the element.

The code I have is not functioning properly.

Any help is greatly appreciated.

$('#elementname').css(< position : "absolute" >); $('#elementname').css(< top : "50%" >); $('#elementname').css(< left : "50%" >); $('#elementname').css(< marginTop : ("-" + parseInt($('#elm-height').val()) / 2) + "px" >); $('#elementname').css(< marginLeft : ("-" + parseInt($('#elm-width').val()) / 2) + "px" >); 

Combine the process of addition with parenthesis .

Instead of being just concatenating «-» , consider multiplying that value with -1 .

$('#elementname').css(< position : "absolute" >); $('#elementname').css(< top : "50%" >); $('#elementname').css(< left : "50%" >); $('#elementname').css(< marginTop : ((-1 * parseInt($('#elm-height').val())) / 2) + "px" >); $('#elementname').css(< marginLeft : ((-1 * parseInt($('#elm-width').val())) / 2) + "px" >); 

JQuery set top and left half of elements width and height, What I’m trying to do is simple. I grab my elements height, and divide that by 2, and set that as my elements margin-top and margin-left css

Источник

.offset()

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

Contents:

.offset() Returns: Object

Description: Get the current coordinates of the first element in the set of matched elements, relative to the document.

version added: 1.2 .offset()

The .offset() method allows us to retrieve the current position of an element (specifically its border box, which excludes margins) relative to the document. Contrast this with .position() , which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is more useful.

.offset() returns an object containing the properties top and left .

Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for margins set on the document element.

While it is possible to get the coordinates of elements with visibility:hidden set, display:none is excluded from the rendering tree and thus has a position that is undefined.

Читайте также:  Python function arguments example

Additional Notes:

  • The number returned by dimensions-related APIs, including .offset() , may be fractional in some cases. Code should not assume it is an integer. Also, dimensions may be incorrect when the page is zoomed by the user; browsers do not expose an API to detect this condition.

Examples:

Access the offset of the second paragraph:

Источник

Jquery style top

I tried to set the top state of the footer div with the height value from the text div., Meta Stack Overflow , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , Stack Overflow Public questions & answers

You will need to set the css property ‘top’ on the #footer div, not call .top() on the div itself.

$("#footer").css('top', $("#text").height() + "px"); 

Answer by Darian Bautista

Description: Get the computed style properties for the first element in the set of matched elements.,Description: Set one or more CSS properties for the set of matched elements.,This example sets the widths of the matched elements to incrementally larger values.,As with the .prop() method, the .css() method makes setting properties of elements quick and easy. This method can take either a property name and value as separate parameters, or a single object of key-value pairs.

   div   

Answer by Prince English

How to add options to a select element using jQuery?,How to redirect to a particular section of a page using HTML or jQuery?,How to get selected text from a drop-down list using jQuery?,How to get all selected checkboxes in an array using jQuery ?

Answer by Azariah Norton

Источник

CSS set div ‘top’ with jquery from div ‘height’

You will need to set the css property ‘top’ on the #footer div, not call .top() on the div itself.

$("#footer").css('top', $("#text").height() + "px"); 

Solution 2

Solution 3

  

Solution 4

 $('#footer').style.css("top",$('#text').style.css("height")); 

Denny Mueller

Comments

I have a template with lots of absolute positioning, now my main text div has a dynamic height and I need a dynamic footer which follows after this. I tried to set the top state of the footer div with the height value from the text div.

 $('#footer').css('top', $('#text').outerHeight() + 'px'); 

Blazemonger

jAndy

@mblase75: jQuery (the browser actually), would just create that css property if it’s not already filled. More correctly, all css properties are available anytime, it just depends whether or not those have a value or not.

Blazemonger

I misread the question — however, it might be worth pointing out the (unlikely here) complication that would result if both top and bottom css properties are set at the same time. If the OP is manipulating someone else’s code, then the bottom property should be explicitly cleared to be safe.

Источник

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