So che è possibile impostare più proprietà CSS in questo modo:Ottenere più proprietà CSS con jQuery
$('#element').css({property: value, property: value});
Ma come faccio ad avere più proprietà con i CSS? C'è qualche soluzione?
So che è possibile impostare più proprietà CSS in questo modo:Ottenere più proprietà CSS con jQuery
$('#element').css({property: value, property: value});
Ma come faccio ad avere più proprietà con i CSS? C'è qualche soluzione?
È possibile creare la propria funzione di jQuery per fare questo:
//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;
};
Ecco una demo: http://jsfiddle.net/6qfQx/1/ (controllare il log della console per visualizzare l'output)
Questa funzione richiede una matrice da passare nel contenere le proprietà CSS da cercare. Uso di questo sarebbe qualcosa di simile: il metodo css
var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element
Sì, avrei fatto lo stesso. Mi sono semplicemente chiesto perché questo non è già integrato. È logico, dal momento che è possibile impostare una singola proprietà o impostare più proprietà. Ho assunto automaticamente che tu possa ottenere una singola proprietà e persino ottenere più proprietà (passando un array a .css()) ma sembrano dimenticarlo. –
Il modo più semplice? Lascia cadere il jQuery.
var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.
di jQuery (a partire da 1,9) dice che si può passare un array di stringhe di proprietà e restituirà un oggetto con coppie chiave/valore.
esempio:
$(elem).css([ 'property1', 'property2', 'property3' ]);
Inoltre, FWIW questo metodo è più veloce di chiamare '.css()' più volte ... chi avrebbe pensato? ;) [jsperf] (http://jsperf.com/jquery-multiple-css-get) – lakenen
@lakenen [proprietà] (http://jsperf.com/jquery-dom-get-multiple-css) il tuo risultato:) – peipst9lker
@ peipst9lker, ovviamente JS semplice è più veloce di jQuery! Però, allora devi hackerare il supporto del browser (currentStyle vs getComputedStyle). Tradeoffs ... – lakenen
Vuoi dire che si vuole una mappa con un dato insieme di proprietà CSS? –
Cosa intendi per ottenere più proprietà CSS? –