front end mobileWindow.js The 0.0.1 version of the framework was officially released, and its shortcomings are expected to be pointed out

Time:2021-3-3

mobileWindow.js

Because the company’s new project needs to achieve similar app operation in the mobile terminal, in order to quickly develop, of course, we hope to find a ready-made third-party class library to realize the relevant functions, but after a few days, we still haven’t found a particularly suitable one, so we started to write a simple framework to realize the numerous needs of the project.

The main function of this library is to let users open the mobile page as if they are using app. The source code is used for reference mobileSelect.js The idea of this third-party tool class framework is based on Vue.

GitHub address:link

function

  • Slide selection box
  • Manual input box, support content verification
  • Label switch different boxes

characteristic

  • Native JS mobile terminal selection control, does not rely on any library
  • You can pass in an ordinary array or a JSON array
  • According to the length of the incoming parameters, the corresponding number of columns can be automatically rendered, and single to multiple selection is supported
  • Automatic identification of cascading
  • After successful selection, the user-defined callback function callback() is provided to return the current selection index position and the selected data (array / JSON)
  • At the end of each gesture sliding, a callback function transitionend() is provided to return the current selection index position and the selected data (array / JSON)
  • After the control has been instantiated, the update function can be provided to render again, which can be used to obtain data asynchronously or to change the selected data after click interaction
  • Provides relocation functions
  • Can echo (when entering the page for the second time, the position selected by history can be displayed)

demonstration

Mobile page preview:

For real project experience, please open the mobile terminal:link

Maybe because of the account problem, some students can’t see the full function, you can use thedemoView all the features in the directory

introduce

Method 1 label introduction:
<link rel="stylesheet" type="text/css" href="assets/styles/mobileWindow.css">
<script type="text/javascript"></script>
Mode 2 NPM:
npm install mobile-window -D

Import in your JS file:

import MobileWindow from 'mobile-window'

Selection box (no label) – quick use

① Common array format – non linkage
< div id = "trigger 1" > < / div > <! -- don't miss this trigger -- > in the page

<script type="text/javascript">
var mobileSelect1 = new MobileSelect({
    trigger: '#trigger1',
    Title: 'single choice',
    wheels: [
                {data: ['sunday ',' Monday ',' Tuesday ',' Wednesday ',' Thursday ',' Friday ',' Saturday ']}
            ],
    Position: [2] // initialize positioning
});
</script>
② JSON format – non linkage
<div id="trigger2"></div>

<script type="text/javascript">
var mobileSelect2 = new MobileSelect({
    trigger: '#trigger2',
    Title: 'region selection',
    wheels: [
                {data:[
                    {ID: '1', value: 'near'},
                    {ID: '2', value: 'Shangcheng district'},
                    {ID: '3', value: 'Xiacheng'},
                    {ID: '4', value: 'Jianggan District'},
                    {ID: '5', value: 'Gongshu District'},
                    {ID: '6', value: 'West Lake District'}
                ]},
                {data:[
                    {ID: '1', value: '1000 m'},
                    {ID: '2', value: '2000 m'},
                    {ID: '3', value: '3000 m'},
                    {ID: '4', value: '5000 m'},
                    {ID: '5', value: '10000 m'}
                ]}
            ],
    callback:function(indexArr, data){
        console.log (data); // returns the selected JSON data
    }
});
</script>
design sketch:
③ JSON format linkage
<div id="trigger3"></div>

<script type="text/javascript">
  var mobileSelect3 = new MobileSelect({
      trigger: '#trigger3',
      Title: 'region selection linkage',
      wheels: [
                  {data:[
                      {
                          id:'1',
                          Value: 'nearby',
                          childs:[
                              {ID: '1', value: '1000 m'},
                              {ID: '2', value: '2000 m'},
                              {ID: '3', value: '3000 m'},
                              {ID: '4', value: '5000 m'},
                              {ID: '5', value: '10000 m'}
                          ]
                      },
                      {ID: '2', value: 'Shangcheng district'},
                      {ID: '3', value: 'Xiacheng'},
                      {ID: '4', value: 'Jianggan District'},
                      {ID: '5', value: 'Gongshu District'},
                      {ID: '6', value: 'West Lake District'}
                  ]}
              ],
      position:[0,1],
      callback:function(indexArr, data){
          console.log (data); // returns the selected JSON data
      }
  });
  </script>
design sketch:
④ How to use it in Vue cli
npm install mobile-select -D
<template>
    <div>
        < div id = "trigger4" > single item selection < / div >
    </div>
</template>

<script>
    import MobileSelect from 'mobile-select'

    export default {
        mounted() {
            var mobileSelect4 = new MobileSelect({
                trigger: "#trigger4",
                Title: "single choice",
                wheels: [
                    {data: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]}
                ],
                callback:function(indexArr, data){
                    console.log(data);
                }
            });
        }
    }
</script>
⑤ Data field name mapping
<div id="trigger5"></div>

<script type="text/javascript">
    //Suppose the field name of your data is ID, title, children
    //It does not match the ID, value and children field names of mobileselect
    //You can use the keymap attribute to map field names
    var mobileSelect5 = new MobileSelect({
        trigger: '#trigger5',
        Title: 'data field name mapping',
        wheels: [
                    {data:[
                        {
                            id:'1',
                            title:'A',
                            children:[
                                {id:'A1',title:'A-a'},
                                {id:'A2',title:'A-b'},
                                {id:'A3',title:'A-c'}
                            ]
                        },
                        {
                            id:'1',
                            title:'B',
                            children:[
                                {id:'B1',title:'B-a'},
                                {id:'B2',title:'B-b'},
                                {id:'B3',title:'B-c'}
                            ]
                        },
                    ]}
                ],
        keyMap: {
            id:'id',
            value: 'title',
            childs :'children'
        },
        callback:function(indexArr, data){
            console.log(data);
        }
    });
</script>

Input box (no label) – quick use

Input content
<div id="trigger-input"></div>

var mobileWindowInput = new MobileWindow({
    // trigger: '#lease-type-trigger',
    //Title: 'rent type options',
    trigger: {
        type: 'input',
        element: '#trigger-input',
    },
    Title: 'please input content',
    transitionEnd:function(indexArr, data){
        //console.log(data);
    },
    callback:function(data){
        console.log(data);
        // mobileWindowRental.validateRegex(123);
        // if(regInt.test(data.valueInput)) {
        document.getElementById('trigger-input').innerHTML = data['valueInput']

    }
});
Input content – verify content format
<div id="month-amount-wrapper"></div>

var mobileWindowRental = new MobileWindow({
    // trigger: '#lease-type-trigger',
    //Title: 'rent type options',
    trigger: {
        type: 'input',
        element: '#month-amount-wrapper',
    },
    Title: 'please enter the amount',
    inputTrim: true,
    inputCheckType: ['number'],
    transitionEnd:function(indexArr, data){
        //console.log(data);
    },
    callback:function(data){
        console.log(data);
        // mobileWindowRental.validateRegex(123);
        // if(regInt.test(data.valueInput)) {
        if(data['checkType'][0]) {
            document.getElementById('month-amount-wrapper').style.color = '#000000';
            document.getElementById('month-amount-wrapper').innerHTML = data.valueInput;
        } else {
            Var strprompt ='Please fill in the integer ';
            document.getElementById('month-amount-wrapper').style.color = '#000000';
            document.getElementById('month-amount-wrapper').innerHTML = strPrompt;
        }

    }
});

Selection box (labeled) – quick use

<div id="trigger6" class="trigger-tag-selector">
    < div id = "House floor container" > floor < / div >
    < div id = "house elevator container" > elevator < / div >
</div>
var floorArr = [];
var floorTotalArr = [];

Var floorneed = 53; // 50 layers in total
for(var iFloor = 0; iFloor<floorNeed; iFloor++) {
    Floorarr [iflloor] = iflloor-2 + 'layer';
}

for(var iFloor = 0; iFloor<floorNeed-3; iFloor++) {
    Floortotalarr [iflloor] ='total '+ (iflloor + 1) +'layer';
}

var arrHouseFloor = [
    floorArr,
    floorTotalArr,
];

Var arrhouseelevator = ['with elevator ',' without elevator '];

var arrTypes = [arrHouseFloor, arrHouseElevator];
var mobileSelectFloorElevator = new MobileWindow({
    // trigger: '#lease-type-trigger',
    //Title: 'rent type options',
    trigger: {
        type: ['select', 'select'],
        element: ['#house-floor-container', '#house-elevator-container'],
        Tags: ['floor ','elevator'],
    },
    Title: ['Please select floor ','Please select elevator'],
    wheels: [
        {
            data: arrTypes,
        },
    ],
    Position: [0, 0], // which is selected by default when initialization positioning is opened? If not, it is 0 by default
    transitionEnd:function(indexArr, data){
        //console.log(data);
    },
    beforeCreate: function() {

    },
    created: function () {
        //'This' points to VM instance
        console.log('a is: ' + this.a)
    },
    beforeMount: function() {

    },
    callback: function(tagIndex, indexArr, data){
        console.log(tagIndex, '/', indexArr, '/', data);

    }
});

parameter

option Default value type describe
trigger Required parameter has no default value String ID / class / tag of trigger object
wheels Required parameter has no default value Array Data source, data to be displayed
callback function(indexArr, data){} function Select the callback function triggered after success, and return indexarr and data
transitionEnd function(indexArr, data){} function The callback function triggered after the end of each gesture sliding returns indexarr and data
cancel function(indexArr, data){} function The returned values are indexarr and data, which are the values of the last click of the confirm button
onShow function(e){} function Display the callback function triggered by the control, and the return parameter is the object itself
onHide function(e){} function The callback function triggered after hiding the control, and the return parameter is the object itself
title '' String Control title
position [0,0,0,…] Array Initial positioning
connector ' ' String When there are multiple wheels, the connector in the middle of multiple values is blank by default
ensureBtnText 'confirm' String Confirm the text content of the button
cancelBtnText 'Cancel' String Cancel the text content of the button
ensureBtnColor '#1e83d3' String Confirm the text color of the button
cancelBtnColor '#666666' String The text color of the Cancel button
titleColor '#000000' String The text color of the control title
titleBgColor '#ffffff' String The background color of the control title
textColor '#000000' String The color of the text inside the wheel
bgColor '#ffffff' String Wheel background color
maskOpacity 0.7 Number mask opacity
keyMap {id:'id', value:'value', childs:'childs'} Object Field name mapping is applicable to the data format of field name mismatch ID, value, children
triggerDisplayData true Boolean Whether trigger’s innerHTML becomes the selected data when you click confirm.
(if there are other elements in trigger, you can set it to false; if you need to display data in other places, you can use the data returned by callback to splice it by yourself.)
Note: the meaning of the parameters returned in the callback function is as follows
  • Indexarr is the currently selected index array. For example, [0,0,1] represents three wheels. The selected data is the 0th data of the first wheel, the 0th data of the second wheel, and the 1st data of the third wheel
  • Data is the currently selected JSON data, such as [{ID: ‘1’, value: ‘hello’}, {ID: ‘2’, value: ‘world’}]

Function function:

Function name parameter describe
show() Acanthopanax Manual display pop-up components
hide() Acanthopanax Manually hide pop-up components
setTitle() string Sets the title of the control
locatePosition() sliderIndex, posIndex Pass in the position array and reposition the selected position of the wheel
updateWheel() sliderIndex, data Re render the specified wheel
updateWheels() data Re render all wheels (cascade data format only)
getValue() Acanthopanax Gets the value of the component selection
Note: the meaning of parameters to be transferred in function function is as follows
  • Sliderindex represents the index of the wheel to be modified
  • Posindex stands for location index
① Function demo:
<div id="day"></div>

var mySelect = new MobileSelect({
    trigger: '#day',
    wheels: [
                {data: ['sunday ',' Monday ',' Tuesday ',' Wednesday ',' Thursday ',' Friday ',' Saturday ']},
                {data:['08:00','09:00','10:00','11:00','12:00','13:00','14:00']}
            ],
    Position: [1,1] // initialize positioning. Select the option at index 1 for both wheels
});

//----------------------------------------------
//After the basic instantiation, the instance is operated with function functions

//  mySelect.setTitle ('La La La (๑̀ㅁ́ฅ));
//Sets the title of the control

// mySelect.updateWheel(0,['sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']);
//Update the data of the 0 th wheel and change the data into the day of the week in English

// mySelect.locatePosition(1,0);
//Reposition the position of the first wheel and change the 0 th data of the first wheel to the currently selected one.
//(the first wheel refers to the right wheel, and the left wheel is the 0 th wheel)

Basic instance → after function operation

② Ajax asynchronous data filling demo
<! -- non cascading format

<div id="trigger6"></div>

<script type="text/javascript">
    var mobileSelect6 = new MobileSelect({
        trigger: '#trigger6',
        Title: 'Ajax padding data - non cascading',
        wheels: [
                    {data:[
                        {ID: '1', value: 'please select region'},
                    ]},
                    {data:[
                        {ID: '1', value: 'please select distance'},
                    ]}
                ],
        callback:function(indexArr, data){
            console.log(data);
        }
    });

    $.ajax({
        type: "POST",
        url: "xxxx",
        data: {},
        dataType: "json",
        success: function(res){
            //Here we assume that the res.data.area For:
            // [
            //{ID: '1', value: 'near'},
            //{ID: '2', value: 'Futian District'},
            //{ID: '3', value: 'Luohu District'},
            //{ID: '4', value: 'Nanshan District'}
            // ]

            //Here we assume that the res.data.distance For:
            // [
            //{ID: '1', value: '200m'},
            //{ID: '2', value: '300 m'},
            //{ID: '3', value: '400m'}
            // ]

            mobileSelect6.updateWheel(0,  res.data.area ); // change the 0 th wheel
            mobileSelect6.updateWheel(1,  res.data.distance ); // change the first wheel
        }
    });
</script>
</script>

<! -- concatenation format ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

<div id="trigger7"></div>

<script type="text/javascript">
    var mobileSelect7 = new MobileSelect({
        trigger: '#trigger7',
        Title: 'ajax data filling cascade',
        wheels: [
                    {data:[
                        {
                            id:'1',
                            value:'',
                            childs:[
                                {id:'A1',value:''},
                            ]
                        }
                    ]}
                ],
        callback:function(indexArr, data){
            console.log(data);
        }
    });

    $.ajax({
        type: "POST",
        url: "xxxx",
        data: {},
        dataType: "json",
        success: function(res){
            //Here we assume that the res.data For:
            // [{
            //     id:'1',
            //Value: 'updated data',
            //     childs:[
            //         {id:'A1',value:'apple'},
            //         {id:'A2',value:'banana'},
            //         {id:'A3',value:'orange'}
            //     ]
            // }]
            mobileSelect7.updateWheels(res.data);
        }
    });
</script>

How to echo the selected location

There is an indexarr parameter in the callback function, which is an array recording the currently selected position
After the array is converted into a string, it can be saved in a hidden field or other ways and passed to the background.
The next time you open a page,
When instantiating mobilewindow, read the string, convert it into an array, pass it to position, and complete the initialization and positioning.

Project Demo:

Use transitionend(), callback(), updatewheel(), locateposition() functions to achieve the following functions:

  • When selecting the date of the day, it must not exceed the past hour of the day.
  • After selecting the pick-up time, the return time should not exceed the pick-up time (including date and time).

Update log

July 3, 2020 [update]

  • Add the function of using label to switch different sliding boxes
  • After you click an option, you will automatically change the content of the div and return to the selected result instead

July 5, 2020 [update + amendment]

  • Fix the problem of multi-level display error after label switching
  • Add the function of pop-up input box

July 8, 2020 [update + amendment]

  • Add input box content verification

July 10, 2020 [amendment]

  • Adjust project structure

July 11, 2020 [amendment]

  • Optimization example code
  • Write examples

licence

Copyright (c) 2020-present, Abbott Liu

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]