2012-03-03 6 views
1

私は、jQueryのドラッグ&ドロップ機能と、要素のサイズ変更などを使用しているWebプロジェクトに取り組んでいます。ブラウザやリロードを閉じるたびに、すべてがゼロに戻ります。状態を少しでも維持したいので、すべての変更を記録するのではなく、環境全体を保存して環境をリロードする方が簡単だと思っています。現在のcss環境を記録する方法は?

jQueryを使用して、すべての要素をループしなくても、すべての要素のすべてのプロパティをループすることなく、完全なCSS環境をJavaScript変数に格納しようとしています。

私はそれは同じくらい簡単かもしれない期待していたとして:

var cssEnvironment = document.css(); 

とウィンドウが閉じますときに、ブラウザが終了し、ブラウザリニューアルオープンし、ページがリニューアルオープン、私はアクションを逆にします。

document.css() = cssEnvironment; 

すべてが復元されます。これに類似した機能を得る方法はありますか?

+1

は多分これはあなたのケースで動作しますhttp://stackoverflow.com/questions/2758286/save-all -css-properties-of-element-using-jqueryを試してください – dotoree

+0

各要素のインラインスタイルの値を保存する必要があります... –

+0

'document.css()' - それほど単純ではありません: ) – maxedison

答えて

0

jQueryでドラッグアンドドロップとサイズ変更を処理しているので、これらの変更はすべてインラインスタイルに適用されます。外部のスタイルシートと<style>ブロックは変更されません。

は、要素をループする必要がありますが、各プロパティをループする必要はありません。要素ごとにstyle属性を取得するだけです。後でこの状態を読み込み、これらのスタイルを特定の要素に割り当てると、idの要素のみを扱うことになります(そうしないと、後で設定することができなくなります)。

このデモはJSONオブジェクトを作成し、localStorageに保存します。

デモ:http://jsfiddle.net/ThinkingStiff/VLXWs/

スクリプト:

function saveState() { 
    var elements = document.querySelectorAll('body *'), 
     state = []; 
    for(var index = 0; index < elements.length; index++) { 
     if(elements[index].id && elements[index].style.length) { 
      state.push({ id:elements[index].id, style: elements[index].style.cssText }); 
     }; 
    }; 
    window.localStorage.setItem('state', window.JSON.stringify(state)); 
}; 

function loadState() { 
    var state = window.localStorage.getItem('state'); 
    if(state) { 
     var styles = window.JSON.parse(state); 
     for(var index = 0; index < styles.length; index++) { 
      document.getElementById(styles[index].id).style.cssText = styles[index].style; 
     }; 
    }; 
}; 

document.getElementById('one').addEventListener('click', function() { 
    this.style.color == 'green' ? this.style.color = 'black' : this.style.color = 'green'; 
}); 
document.getElementById('two').addEventListener('click', function() { 
    this.style.color == 'red' ? this.style.color = 'black' : this.style.color = 'red'; 
}); 
document.getElementById('three').addEventListener('click', function() { 
    this.style.color == 'blue' ? this.style.color = 'black' : this.style.color = 'blue'; 
}); 
document.getElementById('save').addEventListener('click', saveState); 

loadState(); 

HTML:

<div id="one">click to toggle</div> 
<div id="two">click to toggle</div> 
<div id="three">click to toggle</div> 
<button id="save">save</button> 
<div>toggle colors, save, reload page</div> 
関連する問題