search
HomeWeb Front-endJS TutorialjQuery return positioning plug-in example tutorial

jQuery return positioning plug-in example tutorial

Jan 12, 2018 am 09:32 AM
jqueryExampleplug-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方法进行拓展,
   其实和直接绑定到$上是一样的效果*/

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

a.插件结构

<p>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
 //这样就可以自定义方法了。

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

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

<p>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

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

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

nbsp;html>


  <meta>
  <meta>
  <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></script>



  <p>
    </p>
          
  • 第一页 第1个li
  •       
  • 第一页 第2个li
  •       
  • 第一页 第3个li
  •       
  • 第一页 第4个li
  •       
  • 第一页 第5个li
  •       
  • 第一页 第6个li
  •       
  • 第一页 第7个li
  •       
  • 第一页 第8个li
  •       
  • 第一页 第9个li
  •       
  • 第一页 第10个li
  •       
  • 第一页 第11个li
  •       
  • 第一页 第12个li
  •       
  • 第一页 第13个li
  •       
  • 第一页 第14个li
  •       
  • 第一页 第15个li
  •       
  • 第二页 第1个li
  •       
  • 第二页 第2个li
  •       
  • 第二页 第3个li
  •       
  • 第二页 第4个li
  •       
  • 第二页 第5个li
  •       
  • 第二页 第6个li
  •       
  • 第二页 第7个li
  •       
  • 第二页 第8个li
  •       
  • 第二页 第9个li
  •       
  • 第二页 第10个li
  •       
  • 第二页 第11个li
  •       
  • 第二页 第12个li
  •       
  • 第二页 第13个li
  •       
  • 第二页 第14个li
  •       
  • 第二页 第15个li
  •     
   <script> /* * 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+&#39;=([^&]*)&#39;; var replaceText = par+&#39;=&#39;+par_value; if (destiny.match(pattern)) { var tmp = &#39;/\\&#39;+par+&#39;=[^&]*/&#39;; tmp = destiny.replace(eval(tmp), replaceText); return (tmp); } else { if (destiny.match(&#39;[\?]&#39;)) { return destiny+&#39;&&#39;+ replaceText; } else { return destiny+&#39;?&#39;+replaceText; } } return destiny+&#39;\n&#39;+par+&#39;\n&#39;+par_value; } var hash = window.location.hash; history.replaceState(null,&#39;&#39;,location.pathname+location.search); url = window.location.href; var newUrl = changeU(url,arg,val) + hash; history.replaceState(null,&#39;&#39;,newUrl); return false; }, removeUrlPar(options){ history.replaceState(null,&#39;&#39;,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,&#39;&#39;,webUrl + "?" + newParamStr); }else{ history.replaceState(null,&#39;&#39;,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(&#39;keepScrollTop&#39;)); }else{ } </script>

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

相关推荐:

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
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)