2012-02-13 17 views

答えて

3

あなたがこれを行うために、独自のjQuery関数を作成することができます:ここで

//create a jQuery function named `cssGet` 
$.fn.cssGet = function (propertyArray) { 

    //create an output variable and limit this function to finding info for only the first element passed into the function 
    var output = {}, 
     self = this.eq(0); 

    //iterate through the properties passed into the function and add them to the output variable 
    for (var i = 0, len = propertyArray.length; i < len; i++) { 
     output[propertyArray[i]] = this.css(propertyArray[i]); 
    } 
    return output; 
}; 

はデモです:http://jsfiddle.net/6qfQx/1/(出力を見るためにあなたのコンソールログを確認してください)

この機能は必要ですルックアップするCSSプロパティを含む配列が渡されます。このため使用法のようなものになります:(1.9のような)

var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']); 
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element 
+0

ええ、私は同じことをやったでしょう。私はちょうどあなたが単一のプロパティを設定したり、複数のプロパティを設定することができるので、これがまだ組み込まれていないのかどうか疑問に思いました。私は自動的にあなたが単一のプロパティを取得し、複数のプロパティを取得することもできると仮定しています(配列を.css()に渡すことになります)が、単にそれらを忘れてしまったようです。 –

11

最も簡単な方法は? jQueryを削除します。

var e = document.getElementById('element'); 
var css = e.currentStyle || getComputedStyle(e); 
// now access things like css.color, css.backgroundImage, etc. 
10

jQueryのCSSのメソッド、プロパティの文字列の配列を渡すことができ、それは、キー/値のペアを持つオブジェクトを返しますと言います。

例:

$(elem).css([ 'property1', 'property2', 'property3' ]); 

http://api.jquery.com/css/

+0

また、FWIWメソッドは '.css()'を複数回呼び出すよりも高速です...誰が考えましたか? ;)[jsperf](http://jsperf.com/jquery-multiple-css-get) – lakenen

+0

@lakenen [所有](http://jsperf.com/jquery-dom-get-multiple-css)あなたの結果: ) – peipst9lker

+0

@ peipst9lker、もちろんプレーンJSはjQueryより高速です!しかし、ブラウザのサポート(currentStyleとgetComputedStyle)をハックする必要があります。トレードオフ... – lakenen

関連する問題

 関連する問題