簡體   English   中英

CSS 將百分比轉換為像素

[英]CSS convert percent to pixels

我在 CSS 中有指定寬度和高度的“div”元素,以百分比表示。
我想通過 JS 腳本獲得以像素表示的寬度和高度。 甚至有可能嗎?

您可以使用

el.clientHeight;
el.clientWidth;

el是對元素的引用)

演示

請注意,這些屬性最初是在 MS IE DHTML 對象模型中引入的。 最近,它們在 2008 年 2 月 22 日的 W3C 工作草案CSSOM 視圖模塊中進行了標准化。

這些屬性得到了廣泛的支持。 但是,舊的非 MS 兼容瀏覽器可能不支持它們。 在這些情況下,您可以使用getComputedStyle

function findSize(el, size) {
    /* size must be 'width' or ' height' */
    return window.getComputedStyle
        ? getComputedStyle(el,null).getPropertyValue(size)
        : el['client'+size.substr(0,1).toUpperCase() + size.substr(1)] + 'px';
}
findSize(el, 'width');
findSize(el, 'height');

演示

瀏覽器對getComputedStyleclientHeight / clientWidth方式的支持至少是:

                 | IE  | Firefox | Chrome | Safari | Opera
-----------------|-----------------------------------------
getComputedStyle | 9   | <=3     | 1      | <=4    | <=10
client           | <=5 | <=3     | 1      | <=4    | <=10

<=n表示至少從版本n支持它,但我無法測試以前的版本)

為此使用window.getComputedStyle()

<div style="wdith:50%">50% width</div>​​​​​​​​​​​​​

(function() {
    var div = document.getElementsByTagName("div")[0];

    console.log(window.getComputedStyle(div, null)["width"]);
}())​

小提琴

支持所有主流瀏覽器和 IE9+。 對於較低版本的 IE,請查看currentStyle

看看這個

jQuery 鍵是:

$("#div").width();

jQuery 鍵是:

$("#div").width($("#div").width());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM