如何确定宽度是否有px或%

How can i tell if a css property such as width ex: width:100% has px or % assigned to it. in chrome for example if i have width:250px; and i do $('div').width() i get 250 whereas if i use percentage, i just get the width in px for the percentage based on my screen resolution.

This should work.

var value = $('#id').get(0).style.width;
var hasPx = value.indexOf('px') >= 0;
var hasPct = value.indexOf('%') >= 0;

JSBin: http://jsbin.com/asewit/2/edit#javascript,html

You can use .style.cssText, which contains the actual CSS code:

$("<div style='width:50px'>").get(0).style.cssText // "width: 50px; "
$("<div style='width:50% '>").get(0).style.cssText // "width: 50%; "

If by "css property" you mean css rule, and not inline style property set directly in the element, there is no fast way to get it. You'd have to:

  1. Query all css rule declarations

  2. Loop through every css rule and check if the element matches the rule and push it into array

  3. Loop through the candidates and take the latest width value, or the latest width value with !important

If you mean inline style, it's so trivial it's hard to understand why the question got so many upvotes:

element.style.width and check if there is a px or % there

edit: here is incomplete demo for the css rule querying:

http://jsfiddle.net/Chjnd/1/

tested in google chrome and firefox