• 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();
    });
  • 相关阅读:
    vue-awesome-swiper 子项目内容高度适配问题
    ajax的原理及应用
    display:none opacity:0以及visibility:hidden的区别
    javascript 创建型设计模式
    圣杯布局和双飞翼布局
    javascript->对象继承
    js 宏任务和微任务
    android->按钮底部定位上移
    ios移动端开发的坑
    jvm系列 (五) ---类加载机制
  • 原文地址:https://www.cnblogs.com/huxiaolin/p/4942574.html
Copyright © 2020-2023  润新知