search
HomeWeb Front-endHTML Tutorial[Original]zepto creates a mobile swipe screen plug-in_html/css_WEB-ITnose

Recently I have been busy replacing jquery 2 in the project with zepto

Because I didn’t want to reference too many zepto packages, I spent some time

zepto is really It’s a lot streamlined, and the source code looks really comfortable

It happened that the project needed a swipe screen plug-in, so I wrote one using zepto

The logic is actually very simple, but there is no When I thought of the test, there were many bugs in touchmove on the old version of the android device browser

It took a while to make compatibility

Rendering

Style 1

Style 2

Call

Normally it should be the html code generated in the background , but I still wrote a set of methods for operating tab pages

The call is simple as follows:

<link rel="stylesheet" href="kslider.css" type="text/css"/><script type="text/javascript"  src="http://zeptojs.com/zepto.js"></script><script type="text/javascript"  src="zepto.kslider.js"></script><script type="text/javascript">    var k;    $(function () {            /*        参数:config        change:tab页变更事件            参数e: 当前页码        tick:自动滚动间隔时间毫秒 (不设置则不自动滚动)        maxWidth:容器最大宽度 (默认有100%)        minWidth:容器最小宽度 (默认有100%)        className:样式类名            "ks_wt_1" 标题栏-方形 (默认)            "ks_wt_2" 标题栏-小圆形            或者你自定义的类名        */        k = $("#divs1").slider({ change: function (e) { console.log(e); }, maxWidth: 360, minWidth: 300 });        //js添加一页并且跳转到第4页        k.add("标题", "内容").tab(3);        //删除页        //k.remove(0);        //小圆形按钮标题  每隔3秒自动滚动 myimg:自己写的css类,控制里面图片大小        $("#divs2").slider({ maxWidth: 300, className: "ks_wt_2 myimg", tick: 3000 });    });</script>

html

<div id="divs1" class="kslider">    <ul class="ks_wt">    <li class="ks_t2">标题1</li>    <li>标题2</li>    <li>标题3</li>    </ul>    <div class="ks_dbox ks_ts">        <div class="ks_warp">            <ul>                <li>text1</li>                <li>text1</li>                <li>text1</li>                <li>text1</li>                <li>text1</li>                <li>text1</li>                <li>text1</li>                <li>text1</li>            </ul>        </div>        <div class="ks_warp">            <img  src="/static/imghwm/default1.png"  data-src="img/img1.jpg"  class="lazy" / alt="[Original]zepto creates a mobile swipe screen plug-in_html/css_WEB-ITnose" >        </div>        <div class="ks_warp">            <ul>                <li>text3</li>                <li>text3</li>                <li>text3</li>                <li>text3</li>                <li>text3</li>                <li>text3</li>            </ul>        </div>    </div></div>

Specific code

css

/*    kslider.css    lxk 2014.08.14    www.cnblogs.com/wingkun*/body{margin:0px;text-align:center;font:12px 微软雅黑;}.kslider{width:100%;overflow:hidden;margin:0 auto;background:#f0f0f0;}.kslider .ks_warp{width:100%;}.kslider .ks_ts{-webkit-transition:500ms;}.kslider .ks_dbox{width:100%;display:-webkit-box;text-align:left;}.kslider .ks_wt{display:-webkit-box;margin:0px;padding:0px;-webkit-box-pack:center;}.kslider .ks_wt li{text-align:center;list-style:none;background: -webkit-linear-gradient(top, #AAAAAA 0%,#979797 100%);color: #fff;}.ks_wt_1 .ks_wt li{-webkit-box-flex:1;height:35px;line-height:35px;border-right:solid 1px #BBB;}.ks_wt_2 .ks_wt li{background:-webkit-linear-gradient(top, #e7e7e7 0%,#dfdfdf 100%);text-indent: 20px;height:10px;width:10px;overflow:hidden; border-radius:100%;margin:5px;}.ks_wt_1 .ks_wt .ks_t2{background:-webkit-linear-gradient(top, #e7e7e7 0%,#dfdfdf 100%); color:#000;}.ks_wt_2 .ks_wt .ks_t2{background: -webkit-linear-gradient(top, #AAAAAA 0%,#979797 100%); -webkit-animation:kt2 500ms linear;}@-webkit-keyframes kt2{    0%{-webkit-transform:scale(1);}    100%{-webkit-transform:scale(1.5);}}

js

/*    zepto.kslider.js    lxk 2014.08.14    www.cnblogs.com/wingkun*/ (function ($) {        /*        参数:config        change:tab页变更事件            参数e: 当前页码        tick:自动滚动间隔时间毫秒 (不设置则不自动滚动)        maxWidth:容器最大宽度 (默认有100%)        minWidth:容器最小宽度 (默认有100%)        className:样式类名            "ks_wt_1" 标题栏-方形 (默认)            "ks_wt_2" 标题栏-小圆形            或者你自定义的类名        */        $.fn.slider = function (config) {            config = $.extend({}, { className: "ks_wt_1" }, config);            var b = $(this), tw, timer,            target = b.find(".ks_dbox"),            title = b.find(".ks_wt"),            m = { initX: 0, initY: 0, startX: 0, endX: 0, startY: 0, canmove: false },            currentTab = 0;            b.toggleClass(config.className,true);            if (config.maxWidth) b.css({ maxWidth: config.maxWidth });            if (config.minWidth) b.css({ mixWidth: config.minWidth });            title.on("click", function (e) {                if (e.target == this) return;                toTab($(e.target).index());            });            b.on("touchstart", function (e) {                var et = e.touches[0];                if ($(et.target).closest(".ks_dbox").length != 0) {                    m.canmove = true, m.initX = m.startX = et.pageX;                    m.initY = et.pageY;                    clearTimer();                }            }).on("touchmove", function (e) {                var et = e.touches[0];                if (m.canmove && Math.abs(et.pageY - m.initY) / Math.abs(et.pageX - m.initX) < 0.6) {                    //             if (m.canmove && Math.abs(et.pageX - m.startX) > 10) {                    target.removeClass("ks_ts").css("-webkit-transform", "translate3d(" + (m.endX += et.pageX - m.startX) + "px,0,0)");                    m.startX = et.pageX;                    e.preventDefault();                }            }).on("touchend", function (e) {                if (!m.canmove) return;                target.toggleClass("ks_ts", true);                tw = target.width();                //是否超过了边界                var bl = false, current = Math.abs(m.endX / tw);                if (m.endX > 0) {                    current = m.endX = 0;                    bl = true;                }                else if (m.endX < -tw * (target.children().length - 1)) {                    current = target.children().length - 1;                    bl = true;                }                if (!bl) {                    if (m.endX % tw != 0) {                        //target.css("transform", "translate(" + (m.endX = -tw*Math.abs(Math.round(m.endX/tw))) + "px,0px)");                               var str = parseInt((current + "").split(".")[1][0]);                        if (e.changedTouches[0].pageX > m.initX) {                            //往右                            current = str <= 9 ? Math.floor(Math.abs(current)) : Math.abs(Math.round(m.endX / tw));                        } else {                            //往左                            current = str >= 1 ? Math.floor(Math.abs(current)) + 1 : Math.abs(Math.round(m.endX / tw));                        }                    }                }                toTab(current);                setTimer();                m.canmove = false;            });            var move = function (i) {                target.css("-webkit-transform", "translate3d(" + (m.endX = i) + "px,0,0)");            }            var setIndex = function (i) {                return i < 0 ? 0 : i >= target.children().length ? target.children().length - 1 : i;            }            var toTab = function (i) {                i = setIndex(i), tw = target.width();                move(-tw * i), toTitle(i);                if (currentTab != i && config.change) {                    config.change(i);                }                currentTab = i            }            var toTitle = function (i) {                if (title.length == 0) return;                title.children().toggleClass("ks_t2", false).eq(i).toggleClass("ks_t2", true);            }            var setTimer = function () {                if (!config.tick) return;                if (timer) clearTimer();                timer = setInterval(function () {                    toTab(currentTab >= target.children().length - 1 ? 0 : currentTab + 1);                }, config.tick)            }            var clearTimer = function () {                clearInterval(timer);                timer = null;            }            setTimer();            return {                add: function (t, c) {                    //添加tab                    title.append("<li>" + t + "</li>");                    target.append("<div class=\"ks_warp\">" + c + "</div>");                    return this;                },                remove: function (i) {                    //移除tab                    if (title.children().length == 1) return;                    i = setIndex(i);                    title.children().eq(i).remove();                    target.children().eq(i).remove();                    if (i == currentTab) toTab(0);                    return this;                }, tab: function (i) {                    //设置或者获取当前tab                    return i ? toTab(i) : currentTab;                }            }        }    })(Zepto);

Others

  • Only the basic zepto is quoted in the demo. In fact, its touch.js on the mobile side is also very necessary. After quoting You can replace the click in the code with zepto's tap event
  • Address: https://github.com/madrobby/zepto/blob/master/src/touch.js#files

  • Container Please pay attention to the box layout and internal html style used
  • Only supports most webkit kernel browsers
  • Testing needs to be carried out on mobile devices, chrome is required on the computer, F12 is opened, and in the console Next to it, camouflage the environment, as shown below:
  • Released in a hurry, please point out if there are any mistakes, demo download: here

    I have a lot of free time after work... I'm here to look for a part-time job!

    asp.net/js/jquery/html5/css3/Experienced in mobile front-end

    (Coordinates [Changsha], Industry [Lottery Industry] -- if necessary)

    Please support me!

    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
    Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

    HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

    Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

    A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

    How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

    Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

    How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

    How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

    How to modify the playback control style of HTML videoHow to modify the playback control style of HTML videoApr 30, 2025 pm 03:18 PM

    The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

    What problems will be caused by using native select on your phone?What problems will be caused by using native select on your phone?Apr 30, 2025 pm 03:15 PM

    Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

    What are the disadvantages of using native select on your phone?What are the disadvantages of using native select on your phone?Apr 30, 2025 pm 03:12 PM

    What are the disadvantages of using native select on your phone? When developing applications on mobile devices, it is very important to choose the right UI components. Many developers...

    How to optimize collision handling of third-person roaming in a room using Three.js and Octree?How to optimize collision handling of third-person roaming in a room using Three.js and Octree?Apr 30, 2025 pm 03:09 PM

    Use Three.js and Octree to optimize collision handling of third-person roaming in the room. Use Octree in Three.js to implement third-person roaming in the room and add collisions...

    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

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    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 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor