由于您正在处理拖放操作并在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>
也许这将工作你的情况http://stackoverflow.com/questions/2758286/save-all -css-properties-of-element-using-jquery尝试一下 – dotoree 2012-03-03 19:09:31
你必须为每个元素保存内联样式的值...... – 2012-03-03 19:09:41
'document.css()' - 不会那么简单: ) – maxedison 2012-03-03 19:09:55