JQuery技巧

返回顶部按钮

你可以利用 animate 和 scrollTop 来实现返回顶部的动画,而不需要使用其他插件。

// Back to top
$('a.top').click(function () {
  $(document.body).animate({scrollTop: 0}, 800);
  return false;
});<!-- Create an anchor tag --><a class="top" href="#">Back to top</a>

预加载图片

如果你的页面中使用了很多不可见的图片(如:hover 显示),你可能需要预加载它们:

$.preloadImages = function () {  for (var i = 0; i < arguments.length; i++) {
    $('<img>').attr('src', arguments[i]);
  }
};

检查图片是否加载完成

$('img').load(function () {
  console.log('image load successful');
});

你可以把 img 替换为其他的 ID 或者 class 来检查指定图片是否加载完成。

阻止链接加载

有时你不希望链接到某个页面或者重新加载它,你可能希望它来做一些其他事情或者触发一些其他脚本,你可以这么做:

$('a.no-link').click(function (e) {
  e.preventDefault();
});

验证元素是否为空

$(document).ready(function() {
  if ($('#id').html()) {
     // do something
   }
});

替换元素

$(document).ready(function() {
   $('#id').replaceWith('
<DIV>I have been replaced</DIV>
 
');
});

使元素居屏幕中间位置

$(document).ready(function() {
  jQuery.fn.center = function () {
        this.css("position","absolute");
              this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
                    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
                          return this;
  }
  $("#id").center();
});

写自己的选择器

$(document).ready(function() {
   $.extend($.expr[':'], {
       moreThen1000px: function(a) {
                  return $(a).width() > 1000;
      }
   });
  $('.box:moreThen1000px').click(function() {
        // creating a simple js alert box
      alert('The element that you have clicked is over 1000 pixels wide');
  });
});

与其他Javascript类库冲突解决方案

To avoid conflict other libraries on your website, you can use this jQuery Method, and assign a different variable name instead of the dollar sign.

$(document).ready(function() {
   var $jq = jQuery.noConflict();
   $jq('#id').show();
});
原文地址:https://www.cnblogs.com/huxiaolin/p/4942574.html