js实现文章文字大小字号功能完整实例
本文实例讲述了js实现文章文字大小字号功能的方法。分享给大家供大家参考。具体分析如下:
文字大中小是很多网站供用户阅读方便的一个功能,本文实例介绍的文字大中小字号功能可以在用户选择之后打开只要在同网站打开另一篇文章都会根据用户习惯来显示字体大小。
大家一定在某些大型网站看到过文章标题下三个按钮“大”、“中”、“小”,用来照顾不同人的阅读习惯。这里我就要介绍这种方法,而且比它们的还支持自动保存哦~只要选择一次,下次阅读自动调整到喜欢的字号。
JS代码部分:
首先把下边的JS放到JS文件或者script标签里:
jQuery.cookie=function(name,value,options){ if(typeofvalue!='undefined'){ options=options||{}; if(value===null){ value=''; options.expires=-1; } varexpires=''; if(options.expires&&(typeofoptions.expires=='number'||options.expires.toUTCString)){ vardate; if(typeofoptions.expires=='number'){ date=newDate(); date.setTime(date.getTime()+(options.expires*24*60*60*1000)); }else{ date=options.expires; } expires=';expires='+date.toUTCString(); } varpath=options.path?';path='+options.path:''; vardomain=options.domain?';domain='+options.domain:''; varsecure=options.secure?';secure':''; document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join(''); }else{ varcookieValue=null; if(document.cookie&&document.cookie!=''){ varcookies=document.cookie.split(';'); for(vari=0;i<cookies.length;i++){ varcookie=jQuery.trim(cookies[i]); if(cookie.substring(0,name.length+1)==(name+'=')){ cookieValue=decodeURIComponent(cookie.substring(name.length+1)); break; } } } returncookieValue; } }; functionSetFont(size){ $.cookie('Font_size',size,{expires:99999999}); $(".context").css("font-size",size);//.context换成你文章内容的容器 }; $(document).ready(function(){ SetFont($.cookie('Font_size')+'px'); });
注意把代码的.context换成你的文章内容容器。
Html代码部分:
然后在需要的地方调用下边的代码:
<ahref="javascript:SetFont(16)">大</a> <ahref="javascript:SetFont(14)">中</a> <ahref="javascript:SetFont(12)">小</a>
可以自定义SetFont()函数里的字号以及文字。
希望本文所述对大家基于javascript的web程序设计有所帮助。