0

HTML ファイルで、DOM 要素を作成しました。

<div id="colorOne"></div>

css ファイルに属性を設定します。

#colorOne{
    position: absolute;
    top: 70%;
    left: 8%;
    width: 36px;
    height: 36px;
    border-color: black;
    border-width: 5px;
    border-style: solid;
    background-color: white;    
}

しかし、私が命令するように

$('#colorOne').prop('width');    $('#colorOne').prop('height'); 

要素の属性を で取得したい場合は、 のみが表示colorOneされます。しかし、私が変えれば、私が望むものを手に入れることができることにも気付きました.$.propundefinedpropcss

そして、私が書くなら

<div id="colorOne" style="width:36px;"></div>

そして$.prop作品。

それはなぜなのか知りたいです。ブラウザー エンジンは、これら 2 つの異なる書き込み方法をどのように処理しますか?

(1.インラインスタイル 2..cssファイルに属性を設定)

4

2 に答える 2

1

cssあなたが望むものです。

試す:

$('#colorOne').css('width');    
$('#colorOne').css('height'); 

$.prop、 などnameの属性にアクセスするために使用されます。href

それでも を使用したい場合は、html 要素に ,属性propを設定する必要があります。widthheight

<div id="colorOne" width='36px'></div>
$('#colorOne').prop('width');

widthが要素の属性であるため、上記は機能します#colorOne。いずれにせよ、width要素がjsまたはcss(を使用!important)によって変更された場合、$.prop間違った答えが得られます。しかし$.css、あなたに正しいものを与えるでしょう。

于 2013-06-08T13:25:55.323 に答える
1

jQuery を使用して計算された最終的なスタイルを取得する場合は、 を使用する必要があります.css()

これはgetComputedStyle内部的に使用されるため、いくつかの異なるソースからのスタイルで使用できます。

これを行うためにjQueryが内部的に行うことは次のとおりです。

function (elem, name) {
    var ret, defaultView, computedStyle, width, style = elem.style;

    name = name.replace(rupper, "-$1").toLowerCase();

    if ((defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle(elem, null))) {

        ret = computedStyle.getPropertyValue(name);
        if (ret === "" && !jQuery.contains(elem.ownerDocument.documentElement, elem)) {
            ret = jQuery.style(elem, name);
        }
    }

    // A tribute to the "awesome hack by Dean Edwards"
    // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
    // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
    if (!jQuery.support.pixelMargin && computedStyle && rmargin.test(name) && rnumnonpx.test(ret)) {
        width = style.width;
        style.width = ret;
        ret = computedStyle.width;
        style.width = width;
    }

    return ret;
}

.attrまたは呼び出しを実行すると、スタイルではなく.propHTML 属性/プロパティが読み取られます。属性を読み取ると、それのみが取得され、すべてのスタイルシートなどから実際に計算されたスタイルは取得されません.style

于 2013-06-08T13:30:01.383 に答える