4
4
2010
0

用 jQuery 写了个给页面链接加上提示的小书签

已经不记得是怎样发现Learning jQuery这个博客了。首先看到的是关于在网页中加载 jQuery的几篇博文,非常不错,而且改进后的版本挺人性化的。所给链接上有小书签的链接,这里这不再给出了(不懂e文的童鞋请在页面上搜索“jQuerify”)。

觉得这个博客非常不错,当然不能看完一走了之了。于是订阅之,然后就发现了这个简单的jQuery插件——eztip,这里有作者写的demo,效果图如下:

点击这里,然后把鼠标移到本页的链接上,你也可以看到类似的提示哦!

这是所用到的代码,很简单呵:

$(document).ready(function() {
  $('.tips').eztip('a', {contentAttrs: ['title','href'], opacity: .75});
});

样式还得自己定义一下:

.simple-tip { position: absolute; background-color: #cec; border: 1px solid #393; padding: 6px;}

这个插件有点小问题:当链接位于页面右边缘或者下边缘时,提示仍然会出现在右下方(或者你定义的其它位置),造成出现滚动条并且看不到提示的情况。

不过,既然能在任意页面通过小书签加载 jQuery,何不通过小书签把这个提示也加上呢?于是,仿照 jQuerify 小书签,我自己也写了一个给链接加上提示的小书签。调试它花了我一个小时左右呢,这还是有Vimjsbeautify这个清理 Javascript 的 Vim 插件的帮助的情况下。注意,使用前要先确定页面已加载 jQuery,如果网页没有使用 jQuery 的话就用上面介绍的小书签啦。下面给出这个小书签的代码:

javascript: (function() {
  var el = document.createElement('div'),
  b = document.getElementsByTagName('body')[0];
  msg = '';
  el.style.position = 'fixed';
  el.style.height = '32px';
  el.style.width = '220px';
  el.style.marginLeft = '-110px';
  el.style.top = '0';
  el.style.left = '50%';
  el.style.padding = '5px 10px 5px 10px';
  el.style.zIndex = 1001;
  el.style.fontSize = '12px';
  el.style.color = '#222';
  el.style.backgroundColor = '#f99';
  if (typeof jQuery == 'undefined') {
    msg = 'This page is not using jQuery, sorry!';
    return showMsg();
  }
  function getScript(url, success) {
    var script = document.createElement('script');
    script.src = url;
    var head = document.getElementsByTagName('head')[0],
    done = false;
    script.onload = script.onreadystatechange = function() {
      if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
        done = true;
        success();
      }
    };
    head.appendChild(script);
  }
  getScript('http://plugins.learningjquery.com/eztip/jquery.eztip.js', function() {
    jQuery('body').eztip('a', {
      contentAttrs: ['href', 'title'],
      opacity: .9
    });
    jQuery('.simple-tip').css({
      position: 'absolute',
      zIndex: 9999,
      backgroundColor: '#cec',
      color: '#131',
      border: '1px solid #393',
      padding: '6px'
    });
    msg = 'link tip ready!';
    return showMsg();
  });
  function showMsg() {
    el.innerHTML = msg;
    b.appendChild(el);
    window.setTimeout(function() {
      if (typeof jQuery == 'undefined') {
        b.removeChild(el);
      } else {
        jQuery(el).fadeOut('slow', function() {
          jQuery(this).remove();
        });
        if (otherlib) {
          $jq = jQuery.noConflict();
        }
      }
    },
    2500);
  }
})();

| Theme: Aeros 2.0 by TheBuckmaker.com