js实现文章文字大小字号功能完整实例

  本文实例讲述了js实现文章文字大小字号功能的方法。分享给大家供大家参考。具体分析如下:

  文字大中小是很多网站供用户阅读方便的一个功能,本文实例介绍的文字大中小字号功能可以在用户选择之后打开只要在同网站打开另一篇文章都会根据用户习惯来显示字体大小。

  大家一定在某些大型网站看到过文章标题下三个按钮 “大”、“中”、“小”,用来照顾不同人的阅读习惯。这里我就要介绍这种方法,而且比它们的还支持自动保存哦~只要选择一次,下次阅读自动调整到喜欢的字号。

  JS 代码部分:

  首先把下边的 JS 放到 JS 文件或者 script 标签里:

  

复制代码 代码如下:
jQuery.cookie = function(name, value, options) {

  if (typeof value != 'undefined') {

  options = options || {};

  if (value === null) {

  value = '';

  options.expires = -1;

  }

  var expires = '';

  if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {

  var date;

  if (typeof options.expires == 'number') {

  date = new Date();

  date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));

  } else {

  date = options.expires;

  }

  expires = '; expires=' + date.toUTCString();

  }

  var path = options.path ? '; path=' + options.path : '';

  var domain = options.domain ? '; domain=' + options.domain : '';

  var secure = options.secure ? '; secure' : '';

  document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');

  } else {

  var cookieValue = null;

  if (document.cookie && document.cookie != '') {

  var cookies = document.cookie.split(';');

  for (var i = 0; i < cookies.length; i++) {

  var cookie = jQuery.trim(cookies[i]);

  if (cookie.substring(0, name.length + 1) == (name + '=')) {

  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

  break;

  }

  }

  }

  return cookieValue;

  }

  };

  function SetFont(size){

  $.cookie('Font_size', size, { expires: 99999999 });

  $(".context").css("font-size",size);//.context 换成你文章内容的容器

  };

  $(document).ready(function(){

  SetFont( $.cookie('Font_size') + 'px' );

  });

  注意把代码的 .context 换成你的文章内容容器。

  Html 代码部分:

  然后在需要的地方调用下边的代码:

  

复制代码 代码如下:
<a href="javascript:SetFont(16)">大</a>

  <a href="javascript:SetFont(14)">中</a>

  <a href="javascript:SetFont(12)">小</a>

  可以自定义 SetFont() 函数里的字号以及文字。

  希望本文所述对大家基于javascript的web程序设计有所帮助。