2013-12-15 180 views
1

我需要本地存儲幫助。到目前爲止,我有一些js允許用戶更改div的字體系列,並設法在本地保存用戶選擇。但是,我無法弄清楚如何將字體系列值(即helvetica)應用於div上的重載。Local Storage字體家族

function updateh1family() { 
var selector = document.getElementById('selecth1FontFamily'); 
var family = selector.options[selector.selectedIndex].value; 
var h1 = document.getElementById('edit') 
h1.style.fontFamily = family;  

var font = document.getElementById('edit'); 
font.onchange = function() { 
document.getElementById('edit').style.fontFamily = family; 
localStorage.setItem('font', family); 
} 
font.value = localStorage.getItem('font'); 
font.onchange(); 

if (localStorage.length != 0) { 
document.getElementById('edit').style.fontFamily = localStorage.font; 
document.getElementById('edit').value = localStorage.font; 
}} 
+0

你要分開,其在下拉列表中的變化作出反應,並且在加載事件做出反應的代碼。 –

回答

0

入住此解決方案:http://jsfiddle.net/jy424/2/

var selector = document.getElementById('selecth1FontFamily'), 
    text= document.getElementById('edit'); 

if (localStorage.length != 0) { 
    text.style.fontFamily = localStorage.font; 
    text.value = localStorage.font; 
}else{ 
    localStorage.setItem('font', ''); 
} 

selector.onchange = function(){ 
    var family = this.value; 
    text.style.fontFamily = family; 
    localStorage.font = family; 
} 
0

那麼它的簡單

<script type="text/javascript"> 
    window.onload 
    { 
     if(localStorage.font) 
     { 
      document.getElementById('FontDiv').style.fontFamily = localStorage.font; 
     } 
    } 
</script> 
0

我會建議你使用classes而不是試圖直接操縱的樣式。假設你正在使用庫,jQuery使得這非常簡單。你的標籤說你是,但你的代碼建議不。

.on { font-family: arial; } 

$(function() { 
    localStorage.setItem('class', 'on'); 
    $('#edit').addClass(localStorage.getItem('class')); 
}); 

Fiddle example