简体   繁体   中英

How to know if a DIV width is set in Percentage or Pixel using jQuery

Is it possible to know that if a DIV's width is set in Percentage or Pixel.

if (widthSetAsPixel) {
  //  code for doing something with respect to Pixel
}

if (widthSetAsPercentage) {
  //  code for doing something with respect to Percentage
}

You actually don't want to use jQuery as it will only give you the width in px even if it's set in percent (or some other unit). SO, in order to get the unit of the width you'll want to use window.getComputedStyle . The problem still is that this only gives you the width in px unless the element has display: none;

SO... to get the width in its actual unit use this function I wrote:

function getStyle(el){
    var display = window.getComputedStyle(el).getPropertyValue("display");
    el.style.display = "none";
    var width = window.getComputedStyle(el).getPropertyValue("width");
    el.style.display = display;
    return width;
}

Then to check whether or not the width is a percent do this:

var element = document.getElementById("myElementID");
var widthIsPercent = getStyle(element).indexOf("%") > -1;

This principle is true for other CSS properties as well like height , left , etc.

jsFiddle of it in action: http://jsfiddle.net/dwjqfLsz/

If the width has been set with CSS, you should be able to figure it out like this:

var width = $('#yourDiv').css('width');
var widthSetAsPercentage = width.indexOf('%') > -1;
var widthSetAsPixel = !widthSetAsPercentage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM