0

ローカル ストレージを使用して展開/折りたたみ要素の CSS 設定を記憶する方法を探しています

したがって、私の JavaScript は次のようになります (ID を取得し、展開/折りたたみを処理します)。

function toggleHeight(id, link) {
    var e = document.getElementById(id);

    if(e.style.maxHeight == '450px') {
        e.style.maxHeight = '0px'; 
    } else {
        e.style.maxHeight = '450px';
    }
}

だから私が探しているのは、リンクをクリックして div id を取得し、クリックしたときに変更を保存し、更新時に記憶するものです。

4

3 に答える 3

1

たぶん、このようなもの

var height = localStorage.getItem(id+"-height");

localStorage.setItem(id+"-height", height);
于 2012-10-11T08:57:10.437 に答える
1

ここで約束したように、私の解決策は次のとおりです。

<script type="text/javascript">
function toggleHeight(id, link) {
var e = document.getElementById(id);
var height = localStorage.getItem(id);

if(e.style.maxHeight == '450px' || e.style.maxHeight == 'inherit') {
    e.style.maxHeight = '0px'; 
    localStorage.setItem(id,"closed");
} else {
    e.style.maxHeight = '450px';
    localStorage.setItem(id, "open");
}
}

  function load() { 

var setting
var e
var link
for (x in localStorage){
    setting = localStorage.getItem(x);
    e = document.getElementById(x);
    link = document.getElementById('forumlink'+x);

    if (setting == 'open')
    {
        e.style.maxHeight = '450px';
    }
    else
    {
        e.style.maxHeight = '0px';
    }   
    }
    }

</script>

これは、クリックされたときのdivの状態を保存し、開く/閉じるに設定します

ページの読み込み時に、保存された値を取得し、open/closed 値の後に最大高さ css を設定します。

他の人がこれを利用できることを願っています

于 2012-10-19T09:00:04.353 に答える
0

これが私がそれを解決した方法です:作業フィドル

//extra methods to get and set objects in staid of strings
Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}
//fetch the object or make a new and set constant values    
var toggleState = localStorage.getObject('toggleState') || {},
    MIN_SIZE= '0px',
    MAX_SIZE= '450px';

//shown is an optional parameter
function toggleHeight(id, shown) {
    var e = document.getElementById(id);
    if(shown === true || (typeof shown === "undefined" && e.style.maxHeight == MIN_SIZE)) {
       show(id);
    } else {
       hide(id);
    }
}

function show(id){
    var e = document.getElementById(id);
    e.style.maxHeight = MAX_SIZE;
    toggleState[id] = true;
    localStorage.setObject('toggleState',toggleState);
}
function hide(id){
    var e = document.getElementById(id);
    e.style.maxHeight = MIN_SIZE;
    toggleState[id] = false;
    localStorage.setObject('toggleState',toggleState);
}
//loop over it to set initial values
for(var i in toggleState){
    toggleHeight(i, toggleState[i]);
}

//do manual toggle, hide, show

toggleHeight('someID');​

表示と非表示を分離したので、必要に応じて個別に表示非表示にすることも、トグル メソッドを使用することもできます。

于 2012-10-11T09:26:48.290 に答える