简体   繁体   中英

How to get css properties in relative units (%, em) with $(“selector”).css()?

I used jQuery to get HTML element's css properties. But it doesn't work as well as I want to. So I made a little test:

var div = document.createElement("DIV");
    div.id = "testdiv";
var testZero = $(div).css("width") + " / " + div.style.width;
   $(div).css("width", "50%");
var testOne = $(div).css("width") + " / " + div.style.width;
    document.getElementById("res").appendChild(div);
var testTwo = $(div).css("width") + " / " + div.style.width;
var testThree = $("#testdiv").css("width") + " / " + document.getElementById("testdiv").style.width;

Values of the test variables:

testZero: 0px / ""
testOne: 50% / 50%
testTwo: 670px / 50%
testThree: 670px / 50%

Results are the following:

  • testZero : jQuery version returns 0px. JS version returns "" (empty string), if the rule hasn't been set.
  • testOne : After the rule has been set, both version works correctly.
  • testTwo : JS version works correctly. But as soon as I append the div element, jQuery version only returns px values.
  • testThree : It's the same with re-selecting the element.

The question is:

For example:

$(element).css("width", "50%"); //I set the rule
container.appendChild(element); //I append the element
var width = $(element).css("width"); //And the result is also "50%" not "xxpx"

I created this function:

function getProperty(element, property){
    return (element.style[property] != "") ? element.style[property] : $(element).css(property);
}

Returns the property value set in style="" attribute, or returns the absolute value, if property has not been set.

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