Home Web Front-end JS Tutorial jQuery return positioning plug-in example tutorial

jQuery return positioning plug-in example tutorial

Jan 12, 2018 am 09:32 AM
jquery Example plug-in

本文主要介绍了jQuery返回定位插件的相关知识,具有很好的参考价值。下面跟着小编一起来看下吧,希望能帮助到大家。

一、jQuery 提供开发者开发插件的几种模式

1.$.extend();     //这个方法是绑定在$上面的。可以通过$直接调用

2.$.fn.方法名     //这个方法是绑定在Dom对象上面的可以通过$('').方法名();调用

3.$.widget   //通过jQuery UI 部件工厂模式创建。

二、插件的开发过程

1.$.extend();

这个方法其实很简单,只是像$上面添加了一个静态的方法而已。主要用途是对插件api的扩展.

eg:

//$.extend();为了防止,变量和方法之间的相互污染,我们采用闭包的模式。
  (function($,factory){
    var obj = factory();
    $.extend({
      sayHelloWorld:obj.firstApply,
    })
    $.secondApply = obj.secondApply;
  })(jQuery,function(){
    var obj = {
      firstApply(){
        console.log('hello world');
      },
      secondApply(){
        console.log('直接绑定到$上');
      },
    };
     return obj;
  });
  $.sayHelloWorld();//hello world
  $.secondApply(); //直接绑定到$上
   /*从上面的2种绑定方式可以看出用$.extend();对jQuery方法进行拓展,
   其实和直接绑定到$上是一样的效果*/
Copy after login

2.$.fn.方法名。   (方法名 其实就是插件名)。

a.插件结构

<p id="app">app</p>
//$.fn.插件名字 (logText);
  (function($,factory){

    $.fn.logText = factory();
  })(jQuery,function(){
    var logText = function(){
      console.log(this.text());
      return this;
    }
    return logText;
  });
  $("#app").logText(); //app  通过DOM元素之间调用该方法。并返回该对象。这也是jQuery实现链式操作的技巧。
  var h = $("#app").logText().height(); // app
  console.log(h); //18
 //这样就可以自定义方法了。
Copy after login

在jQuery插件的开发过程中,其实主要是通过第二种模式($.fn.插件名)开发的。因为jQuery的强大之处就是对Dom的操作.

b.一个插件的强大之处就是参提供周全的参数。以及方便使用者对参数进行扩展。

<p id="app">app</p>
   //$.fn.插件名字 (myPuglin);
  (function(global,$,factory){
    var common = factory(); //封装插件使用到的函数。
    $.fn.myPuglin = function(opts){  //插件的名称
      var defaults = {}; //默认的api
      opts = $.extend(defaults,opts || {}); //对api的拓展
      /*
       *
       * 要执行的功能
       * 
       */
      console.log(opts.hello);

      return this;
    }
  })(window,jQuery,function(){
    var common = {
      a(opt){
        return opt;
      },
    };
    return common;
  });
  $("#app").myPuglin({hello:'hello world'}); //hello world
Copy after login

准备工作已经完毕。那么下面会一个插件为列子,来讲解

3.工作中经常用到的列表到详情。返回来需要保留该位置的插件。(返回定位) savePositon();  $.fn.savePosition

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
  <title>Title</title>
  <style>
    @media screen and (max-width: 319px) {
      html {
        font-size: 85.33333px; } }
    @media screen and (min-width: 320px) and (max-width: 359px) {
      html {
        font-size: 85.33333px; } }
    @media screen and (min-width: 360px) and (max-width: 374px) {
      html {
        font-size: 96px; } }
    @media screen and (min-width: 375px) and (max-width: 383px) {
      html {
        font-size: 100px; } }
    @media screen and (min-width: 384px) and (max-width: 399px) {
      html {
        font-size: 102.4px; } }
    @media screen and (min-width: 400px) and (max-width: 413px) {
      html {
        font-size: 106.66667px; } }
    @media screen and (min-width: 414px) {
      html {
        font-size: 110.4px; } }
    /*CSS Reset*/
    body,
    p,
    dl,
    dt,
    dd,
    ul,
    ol,
    li,
    h1,
    h2,
    h3,
    h4,
    h5,
    h6,
    pre,
    code,
    form,
    fieldset,
    legend,
    input,
    textarea,
    p,
    blockquote,
    th,
    td,
    header,
    hgroup,
    nav,
    section,
    article,
    aside,
    footer,
    figure,
    figcaption,
    menu,
    button {
      margin: 0;
      padding: 0; }
    li{
      list-style: none;
    }
    #app{
      width: 100%;
      max-width: 640px;
     }
    li {
      height: 1.2rem;
      width: 100%;
      border-bottom: 1px solid #cccccc;
      text-align: center;
      line-height: 1.2rem;
      font-size: 20px;
    }
  </style>
  <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

</head>
<body>
  <p id="app">
    <ul>
      <li data-page="1" data-url="http://baidu.com?id=1">第一页 第1个li</li>
      <li data-page="1" data-url="http://baidu.com?id=2">第一页 第2个li</li>
      <li data-page="1" data-url="http://baidu.com?id=3">第一页 第3个li</li>
      <li data-page="1" data-url="http://baidu.com?id=4">第一页 第4个li</li>
      <li data-page="1" data-url="http://baidu.com?id=5">第一页 第5个li</li>
      <li data-page="1" data-url="http://baidu.com?id=6">第一页 第6个li</li>
      <li data-page="1" data-url="http://baidu.com?id=7">第一页 第7个li</li>
      <li data-page="1" data-url="http://baidu.com?id=8">第一页 第8个li</li>
      <li data-page="1" data-url="http://baidu.com?id=9">第一页 第9个li</li>
      <li data-page="1" data-url="http://baidu.com?id=10">第一页 第10个li</li>
      <li data-page="1" data-url="http://baidu.com?id=11">第一页 第11个li</li>
      <li data-page="1" data-url="http://baidu.com?id=12">第一页 第12个li</li>
      <li data-page="1" data-url="http://baidu.com?id=13">第一页 第13个li</li>
      <li data-page="1" data-url="http://baidu.com?id=14">第一页 第14个li</li>
      <li data-page="1" data-url="http://baidu.com?id=15">第一页 第15个li</li>

      <li data-page="2" data-url="http://baidu.com?id=16">第二页 第1个li</li>
      <li data-page="2" data-url="http://baidu.com?id=17">第二页 第2个li</li>
      <li data-page="2" data-url="http://baidu.com?id=18">第二页 第3个li</li>
      <li data-page="2" data-url="http://baidu.com?id=19">第二页 第4个li</li>
      <li data-page="2" data-url="http://baidu.com?id=20">第二页 第5个li</li>
      <li data-page="2" data-url="http://baidu.com?id=21">第二页 第6个li</li>
      <li data-page="2" data-url="http://baidu.com?id=22">第二页 第7个li</li>
      <li data-page="2" data-url="http://baidu.com?id=23">第二页 第8个li</li>
      <li data-page="2" data-url="http://baidu.com?id=24">第二页 第9个li</li>
      <li data-page="2" data-url="http://baidu.com?id=25">第二页 第10个li</li>
      <li data-page="2" data-url="http://baidu.com?id=26">第二页 第11个li</li>
      <li data-page="2" data-url="http://baidu.com?id=27">第二页 第12个li</li>
      <li data-page="2" data-url="http://baidu.com?id=28">第二页 第13个li</li>
      <li data-page="2" data-url="http://baidu.com?id=29">第二页 第14个li</li>
      <li data-page="2" data-url="http://baidu.com?id=30">第二页 第15个li</li>
    </ul>
  </p>
</body>
<script type="text/javascript">
  /*
   * 1.为什么我要返回定位呢。肯定是增加用户的体验度。比如你刚看的那条信息挺感
   * 兴趣的,点进详情看完了,回来一看,不见了,是不是很呕心啊。
   * 2.难点在哪里?
   *  难点1:当我们有很多的列表的时候,列表肯定是滚动加载。于是我们直接保存滚动条的位置
   *  的方式可以放弃了。
   *  难点2:我们怎么确定是从详情返回来的?
   * 3.我们该怎么实现呢?
   *  其实我们实现的方式跟保存滚动条的位置差不多。但要对scrollTop的距离进行处理。
   *  a.我们点击这点详情的时候,可视区域列表的条数,可以是一页的数据,可能会是2页数据。
   *  这种情况下我们都要把结果保留下来。
   *  b.当我们点击这条数据的时候存现当前页滚动了多少就可以了。
   *
   *  下面具体看代码:
   */
  (function(global,$,factory){
    var keepScrollTop = 0; //用于最后保存的滚动条的位置
    var tool =factory();
    $.fn.savePosition = function(options){
      var dataPage,logo,objLogo,prevNum,containerHeight = 0,scrollTopDistance = 0,elIndex = 0,
       prevHeight = 0,prevCountPage = 0,prevCountPageDistance = 0,prevDistance = 0,
       prevPageScrollDistance = 0;
      var elements = this;
      var defaults = {
        container:$(window),  //滚动的容器
        logo:"data-url",   // 用于计算在这个容器中的每个LI中的唯一标识量。一般为去详情的连接
        currentPage:"data-page",  //点击当前的li的页码
        pageResize:30,        //与后台交互的每页返回的数量。 默认是30,
        goToDetailElement:$(".go-detail") ,  //滚动的每个列的总对象
        nodeLi:"", //元素节点
        getPageNum:"getPageNum",       //1表示单页数据,2表示双页数据。设置是请求单页数据还是双页数据的标识量。放在URL上。
        urlPageNum:"pageNum",        //用于放到URL上面的参数标识表示当前是几页. pageNum = currentPage  //返回来的时候用这个参数来判断是不是需要滚动
      };
      var settings = $.extend(defaults,options || {});
      dataPage = elements.attr(settings.currentPage);  //求出点击对象位于哪一个页码
      logo = elements.attr(settings.logo);   //求出当前对象的唯一标识量
      containerHeight = parseInt(settings.container.outerHeight());  //容器的高度
      scrollTopDistance = parseInt(settings.container.scrollTop()); //滚动的距离
      elements.parent().find(""+ settings.nodeLi + "["+settings.currentPage + "=" + dataPage +"]").each(function(index, obj){
        objLogo = $(obj).attr(settings.logo);
        elIndex = index;
        if(logo == objLogo){
          prevNum = elements.prevAll().length;
          prevHeight = tool.getDistance(elements.parent().children(),prevNum - elIndex);
          prevCountPage = parseInt(prevNum / settings.pageResize);
          if(scrollTopDistance < prevHeight){
            elements.parent().children().each(function(index,target){
              if(prevCountPage > 0 ){
                if(index < (prevCountPage - 1) * settings.pageResize){
                  prevCountPageDistance += parseInt($(target).outerHeight());
                };
              };
            });
            tool.changeUrlPar(settings.urlPageNum,dataPage - 1);     //当前的页数
            tool.changeUrlPar(settings.getPageNum,2);       //获取双页数据
            keepScrollTop = scrollTopDistance - prevCountPageDistance;          //请求双页数据 向上 减 1;
          }else{
            prevDistance = tool.getDistance(elements.parent().children(),(prevCountPage + 1) * settings.pageResize);
            prevPageScrollDistance = tool.getDistance(elements.parent().children(),prevCountPage * settings.pageResize);
            if(prevDistance < (scrollTopDistance + containerHeight)){
              tool.changeUrlPar(settings.urlPageNum,dataPage);    //点击对象位于当前的页数
              tool.changeUrlPar(settings.getPageNum,2);        //请求双页数据
              keepScrollTop = scrollTopDistance - prevPageScrollDistance;
            }else{
              tool.changeUrlPar(settings.urlPageNum,dataPage);    //点击对象位于当前的页数
              tool.changeUrlPar(settings.getPageNum,1);  //请求单页数据
              keepScrollTop = scrollTopDistance - prevPageScrollDistance;
            };
          };
        };
      });
      tool.setSessionStorage("keepScrollTop",keepScrollTop);   //保存滚动条的位置
      return this;
    };
    $.getSessionStorage = function(opt){
      opt = sessionStorage.getItem(opt);
      return opt;
    };
  })(window,jQuery,function(){
    var tool = {
      changeUrlPar(arg, val){  //改变URL参数
        function changeU(destiny, par, par_value) {
          var pattern = par+'=([^&]*)';
          var replaceText = par+'='+par_value;
          if (destiny.match(pattern))
          {
            var tmp = '/\\'+par+'=[^&]*/';
            tmp = destiny.replace(eval(tmp), replaceText);
            return (tmp);
          }
          else {
            if (destiny.match('[\?]'))
            {
              return destiny+'&'+ replaceText;
            }
            else
            {
              return destiny+'?'+replaceText;
            }
          }
          return destiny+'\n'+par+'\n'+par_value;
        }
        var hash = window.location.hash;
        history.replaceState(null,'',location.pathname+location.search);
        url = window.location.href;
        var newUrl = changeU(url,arg,val) + hash;
        history.replaceState(null,'',newUrl);
        return false;
      },
      removeUrlPar(options){
        history.replaceState(null,'',location.pathname+location.search);
        var newParamStr = "";
        var quotes = window.location.href.indexOf("?");
        if(quotes != -1){
          var webUrl = window.location.href.split("?")[0];
          var paramsStr = window.location.href.split("?")[1].toString();
          if(paramsStr.indexOf("&") != -1){
            var pageIndex = paramsStr.indexOf(options);
            if(pageIndex != -1){
              var pageArr = paramsStr.split("&");
              for(var i = 0; i < pageArr.length; i++){
                if(pageArr[i].match(options)){
                  pageArr.splice(i,1);
                };
              };
              newParamStr = pageArr.join("&");
            }else{
              newParamStr = paramsStr;
            } ;

          }else{
            if(paramsStr.match(options)){
              newParamStr = "";
            }else {
              newParamStr = paramsStr;
            };
          };
          history.replaceState(null,'',webUrl + "?" + newParamStr);
        }else{
          history.replaceState(null,'',w.location.href);
        }
      },
      getDistance(obj,maxNum){
        var h = 0;
        obj.each(function(index,target){
          if(index < maxNum){
            h += parseInt($(target).outerHeight());
          }
        });
        return h;
      },
      setSessionStorage(keyName,opt){
        sessionStorage.setItem(keyName,opt);
        console.log(opt)
      },
    }

    return tool;
  })
  $("li").on("click",function(){
    $(this).savePosition({pageResize:15});
    /*
     *  1.http://localhost/index.php/Home/Web?pageNum=2&getPageNum=1
     * 点击玩了以后url就变成这样了。这时候表示 返回来的时候请求第二页的数据。只请求一次。从第二页开始
     *
     * 2.http://localhost/index.php/Home/Web?pageNum=1&getPageNum=2
     * 这样表示请求也数据。从第一页的数据开始
     *
     */
    var _herf = $(this).attr("data-url");
    window.location.href = _herf;
  });
  //当我们初始化的时候
  var pageNum = 1,getPageNum = 2; //这两个数的值是从URL中获取的。只有从详情返回来 时候,才有

  if(!!pageNum && !!getPageNum){
    //其中还有很多判定,肯定是先获取数据在滚动。。。
    $(window).scrollTop($.getSessionStorage('keepScrollTop'));
  }else{

  }
</script>
</html>
Copy after login

这个返回定位的插件基本就开发完毕了。当然对于实际的项目中,还有很多的改动。比如返回的时候,一定要把设置的标志参数去掉。

相关推荐:

jQuery scrollFix滚动定位插件_javascript技巧

jQuery导航条固定定位效果的实现方法

JavaScript随机生成一定位数的密码的实现方法

The above is the detailed content of jQuery return positioning plug-in example tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the Chrome plug-in extension installation directory? What is the Chrome plug-in extension installation directory? Mar 08, 2024 am 08:55 AM

What is the Chrome plug-in extension installation directory? Under normal circumstances, the default installation directory of Chrome plug-in extensions is as follows: 1. The default installation directory location of chrome plug-ins in windowsxp: C:\DocumentsandSettings\username\LocalSettings\ApplicationData\Google\Chrome\UserData\Default\Extensions2. chrome in windows7 The default installation directory location of the plug-in: C:\Users\username\AppData\Local\Google\Chrome\User

Share three solutions to why Edge browser does not support this plug-in Share three solutions to why Edge browser does not support this plug-in Mar 13, 2024 pm 04:34 PM

When users use the Edge browser, they may add some plug-ins to meet more of their needs. But when adding a plug-in, it shows that this plug-in is not supported. How to solve this problem? Today, the editor will share with you three solutions. Come and try it. Method 1: Try using another browser. Method 2: The Flash Player on the browser may be out of date or missing, causing the plug-in to be unsupported. You can download the latest version from the official website. Method 3: Press the "Ctrl+Shift+Delete" keys at the same time. Click "Clear Data" and reopen the browser.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to unblock Google Chrome plug-in How to unblock Google Chrome plug-in Apr 01, 2024 pm 01:41 PM

How to unblock the Google Chrome plug-in? Many users like to install various useful plug-ins when using Google Chrome. These plug-ins can provide rich functions and services and improve work efficiency. However, some users say that after installing plug-ins in Google Chrome, the plug-ins will always be displayed. is blocked, so how can you unblock the plug-in after encountering this situation? Now let the editor show you the steps to unblock plug-ins in Google Chrome. Friends in need should come and take a look. How to unblock plug-ins in Google Chrome Step 1. When the blocked prompt appears, click the "Control Bar" and select "Install ActiveX Control". 2. Then open the browser "Tools" menu and click "Internet Options". 3.

How Google Chrome allows animation plugins to run How Google Chrome allows animation plugins to run Mar 28, 2024 am 08:01 AM

How does Google Chrome allow animation plugins to run? Google Chrome is very powerful. Many friends like to use this browser to watch video animations. However, if you want to watch various animated videos, you need to install animation plug-ins in the browser. Many friends use Google Chrome. After installing the animation plug-in, I still cannot care about the video. How should I deal with this problem? Next, let the editor show you the specific steps to allow the animation plug-in to run in Google Chrome. Friends who are interested can come and take a look. Specific steps for Google Chrome to allow animation plug-ins to run: 1. First run Google Chrome on your computer, and click the main menu button in the upper right corner of the homepage (as shown in the picture). 2. After opening the main menu, select the "Settings" option below (as shown in the picture). 3. In settings

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

See all articles