如果我创建这样的DIV:
something = $("<div/>", { id: "something" }).css({
width: "100%",
background: "#333333",
height: "3px",
position: "relative",
"-moz-box-sizing": "content-box"
});
并尝试使用以下任一方法获得宽度:
console.log(something.width());
console.log(something.css("width"));
它只返回100.对于我的场景,我有时会使用百分比或特定像素数。
如何确定元素的宽度是百分比还是指定的像素数量?
答案 0 :(得分:4)
答案 1 :(得分:3)
利用indexOf
:
var w = something.css("width");
if (w.indexOf("px") != -1) {
// Do something
}
<强> DEMO 强>
将其追加到正文时,宽度将以像素为单位。您可以通过使用$(window).width()
或从父容器中检索宽度来计算百分比。真的取决于应用程序。