get CSS rule's percentage value in jQuery
76703 просмотра
12 ответа
Let's say the rule is as follows:
.largeField {
width: 65%;
}
Is there a way to get '65%' back somehow, and not the pixel value?
Thanks.
EDIT: Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRules parameter ends up with either null or undefined value.
This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the head tag of the document).
Автор: montrealist Источник Размещён: 12.11.2019 09:55Ответы (12)
49 плюса
There's no built-in way, I'm afraid. You can do something like this:
var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';
Автор: Adam Lassek
Размещён: 13.04.2009 04:09
114 плюса
82 плюса
This is most definitely possible!
You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.
$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);
See my example.
Now... I wonder if I'm first to discover this hack:)
Update:
One-liner
element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');
It will leave behind a hidden element before the </body>
tag, which you may want to .remove()
.
See an example of one-liner.
I'm open to better ideas!
Автор: timofey.com Размещён: 09.11.2013 07:5644 плюса
You could access the document.styleSheets
object:
<style type="text/css">
.largeField {
width: 65%;
}
</style>
<script type="text/javascript">
var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var i=0; i < rules.length; i++) {
var rule = rules[i];
if (rule.selectorText.toLowerCase() == ".largefield") {
alert(rule.style.getPropertyValue("width"));
}
}
</script>
Автор: Gumbo
Размещён: 13.04.2009 04:27
18 плюса
Late, but for newer users, try this if the css style contains a percentage:
$element.prop('style')['width'];
Автор: ddanone
Размещён: 07.06.2016 10:09
10 плюса
A jQuery plugin based on Adams answer:
(function ($) {
$.fn.getWidthInPercent = function () {
var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
return Math.round(100*width)+'%';
};
})(jQuery);
$('body').html($('.largeField').getWidthInPercent());
Will return '65%'. Only returns rounded numbers to work better if you do like if (width=='65%'). If you would have used Adams answer directly, that hadn't worked (I got something like 64.93288590604027). :)
Автор: Leonard Pauli Размещён: 04.09.2012 07:153 плюса
Building on timofey's excellent and surprising solution, here is a pure Javascript implementation:
function cssDimensions(element)
var cn = element.cloneNode();
var div = document.createElement('div');
div.appendChild(cn);
div.style.display = 'none';
document.body.appendChild(div);
var cs = window.getComputedStyle
? getComputedStyle(cn, null)
: cn.currentStyle;
var ret = { width: cs.width, height: cs.height };
document.body.removeChild(div);
return ret;
}
Hope it's helpful to someone.
Автор: Gregory Magarshak Размещён: 06.04.2016 07:291 плюс
I have a similar issue in Getting values of global stylesheet in jQuery, eventually I came up with the same solution as above.
Just wanted to crosslink the two questions so others can benefit from later findings.
Автор: Horst Walter Размещён: 20.08.2011 11:480 плюса
You could put styles you need to access with jQuery in either:
- the head of the document directly
- in an include, which server side script then puts in the head
Then it should be possible (though not necessarily easy) to write a js function to parse everything within the style tags in the document head and return the value you need.
Автор: wheresrhys Размещён: 13.04.2009 04:240 плюса
You can use the css(width) function to return the current width of the element.
ie.
var myWidth = $("#myElement").css("width");
See also: http://api.jquery.com/width/ http://api.jquery.com/css/
Автор: user267867 Размещён: 06.03.2010 10:420 плюса
There's nothing in jQuery, and nothing straightforward even in javascript. Taking timofey's answer and running with it, I created this function that works to get any properties you want:
// gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
// domNode - the node to get properties for
// properties - Can be a single property to fetch or an array of properties to fetch
function getFinalStyle(domNode, properties) {
if(!(properties instanceof Array)) properties = [properties]
var parent = domNode.parentNode
if(parent) {
var originalDisplay = parent.style.display
parent.style.display = 'none'
}
var computedStyles = getComputedStyle(domNode)
var result = {}
properties.forEach(function(prop) {
result[prop] = computedStyles[prop]
})
if(parent) {
parent.style.display = originalDisplay
}
return result
}
Автор: B T
Размещён: 03.10.2016 04:11
0 плюса
Convert from pixels to percentage using cross multiplication.
Formula Setup:
1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)
2.) element_width_percentage = (100 * element_width_pixels) / parent_width_pixels
The actual code:
<script>
var $width_percentage = (100 * $("#child").width()) / $("#parent").width();
</script>
Автор: Zachary Horton
Размещён: 08.12.2017 06:59
Вопросы из категории :
- jquery Прокрутка переполненных DIV с помощью JavaScript
- jquery Экранирование строк HTML с помощью jQuery
- jquery Как сравнить HTML-сущность с JQuery
- jquery Есть ли функция "существует" для jQuery?
- jquery Как удалить все параметры в окне выбора, а затем добавить один вариант и выбрать его с помощью jQuery?
- jquery Получение идентификатора элемента, который вызвал событие
- jquery Как получить результат из модального диалога в JQuery
- jquery Удалите все классы, начинающиеся с определенной строки.
- jquery Как мне остановить эффект в jQuery
- jquery Как показать загрузочный счетчик в jQuery?
- css Как определить, какой из указанных шрифтов был использован на веб-странице?
- css Создание закругленных углов с помощью CSS
- css Как автоматически изменить размер текстовой области с помощью Prototype?
- css Как вы можете настроить номера в упорядоченном списке?
- css Как я могу найти неиспользуемые изображения и стили CSS на веб-сайте?
- css Как заставить нижний колонтитул оставаться внизу веб-страницы?
- css Create a variable in .CSS file for use within that .CSS file
- css Как разместить одно изображение поверх другого в HTML?
- css Как я могу отобразить только часть изображения в HTML / CSS?