简体   繁体   中英

Local Storage font family

I need some help with local storage. So far I have some js which allows the user to change the font family of a div, and it manages to save the users selection locally. However, I can't figure out how to apply the font family value (ie helvetica) to the div on reload.

    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;
 }}

Well it's simple

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

I would advise you to use classes instead of trying to manipulate the styles directly. jQuery makes this very easy, assuming you are using the library. You tags say you are, but your code suggests not.

.on { font-family: arial; }

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

Fiddle example

Check this solution: 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM