JavaScript GOOD 篇

A .BOM Overview

That BOM browser object model, it provides a lot of methods and properties carried out independently of the content of the browser window object interaction, the core object is the window, BOM consists of a series of objects, and each object provides

The window object is the top-level object browser , it has both a dual role.

1, which is an interface to access the browser window js

2. He is a global object variable is defined in the global scope, the function will become properties and methods of the window object, the window can be omitted at the time of the call, the front window of learning dialogs are all learning methods, such as alert ( ), prompt ();

Window.name a special property under 3.window

Second, the text

1. window load event

window.onload is a window (page) load event, when the content of the document is fully loaded will trigger the event, with the window.onload can put js code written on the top of the page elements, such as page content because the window.onload is fully loaded go js code execution

window.onlad traditional way can only be registered once registration event, if the emergence of multiple, subject to a final places

window.addEventListener ( 'load', function () {}), can register multiple

document.addEventListener ( 'DOMContentLoaded', function () {}), only when the DOM is ready to perform, not including style sheets, images, flash, if the page picture too, using the above trigger time will be longer, affecting the user experience , it is possible to consider this

2. Adjust the size of the time window

window.onresize=function();

window.addEventListener=('resize',function(){})

As long as the pixel window size changes, it will trigger this event

Often take advantage of this event to complete responsive layout, window.innerWidth current screen width

3. Timer

①window.setTimeout (calling function, milliseconds delayed); the method is used to define a timer that performs the function is called after expiration of the timer

<Script>
         // this function call, the window may be omitted in front of 
        the window.setTimeout (function () { 
            Alert ( ' 22 is ' ); 
        }, 2000 )
         // or by directly calling the function name 
        function Print () { 
            Alert ( ' 33 is ' ); 
        } 
        the setTimeout (Print, 3000 );
         // pages may have many timers, often add an identifier to the timer, e.g. 
        var TIME1 = the setTimeout (Print, 3000 );
     </ Script>

 ② Clear Timer

window.clearTimeout (timeout ID); the same, window 1 can be omitted

③ The timer setInternal (function calls, the number of milliseconds);

This process was repeated call a function, that every time, went to call once, the rest with a similar setTimeout ()

Clear Timer setInternal ();

window.clearsetInternal(timeout ID)

4.this pointing problem

Under normal circumstances, this final point is that calling it an object

Common global scope or this function the global object window

Who calls this method call who point

This refers constructor instance constructor

5, js is single-threaded, at the same time can only do one thing, such as add and delete nodes, can only be queued, so easily lead to the problem is the time the task is likely to wait too long to load incoherent, in order to solve this problem ·, js appeared in both synchronous and asynchronous

① Synchronization

A task execution is completed before another task to execute, the execution order consistent with the order in which tasks

② asynchronous

Do one thing at the same time can also do other things

Synchronization task

Synchronization tasks are performed on the thread execution stack to form a

Asynchronous tasks

js asynchronous callback function is achieved by

In general, there are three types of asynchronous tasks

1. Ordinary events such as click, resize, etc.

2. Resource load, such as load, error

3. timers, including setTimeout (), setinternal ().

Asynchronous tasks and associated callback functions added to the task list

 

 For example

<Script> 
        the console.log ( . 11 ); 
        the setTimeout (function () { 
            the console.log ( 22 is ); 
        }, 0 ); 
        the console.log ( 33 is );
         // output of the order of 113 322, because the timer callback function 
    </ script>

js enforcement mechanisms

1. First perform the synchronization task execution stack

2. asynchronous tasks (callback function) into the task list

3. Once all tasks execution stack is completed, the system will read sequentially in the order in the task list of asynchronous tasks, it was read by asynchronous tasks waiting for the end state, into the execution stack, started

 

 Since the main thread continue to reacquire the task, perform the task. Reacquisition task, perform the task. Therefore, this mechanism is called an event loop

6.location objects

 If you want to achieve the page jump location.href = 'URL you want to jump';

 

 The first effect of a recession

navigatior objects


navigatior object contains information about the browser, he has a lot of attributes, we often are userAgent, the property can return the value sent by the client to the server's user-agent header

history objects

The window object provides us with a history objects, interact with the historical status of the browser, the object contains a user visited URL (in the browser window).

history objects effect
back() Back function can be achieved
forward() To achieve advancement function
go (parameters)

Achieve forward and backward functions, parameters as a forward a page,

-1 parameter is a back page

offset Overview

Can be dynamically associated attributes obtained using offset position of the element size,

1. The position of parent element is obtained with a positioning element distance

2. The obtained size of the element itself (width height)

3. Note: not return a value with units

 Scroll from page obtained by window.pageXoffset

 

Elements in the visual area client series

client translates the meaning of the client, we make use of the relevant series of client property to obtain the relevant information elements in the visual area, you can get a dynamic border size of the element, the element size by the relevant series of client property.

Immediately execute the function

Two way (function () {} ()) (function () {}) ()

Main functions: to create an independent scope, to avoid naming conflicts

<Script> 
        (function () { 
            the console.log (. 1); 
        } ()); // the second bracket can be viewed as small call functions 
        // parameters may also be used 
        (function (A) { 
            the console.log (A ); 
        } (1)); 
        // or 
        (SUM function () { 
            the console.log (1); 
        } ()); 
    </ Script>

 dpr: physical pixel ratio, pc terminal 1, mobile terminal 2

Scroll scroll element series

scroll translates to mean scrolled using the scroll series of related attributes can be dynamically get the size of the element, the rolling distance.

scroll series of related properties effect
element.scrollTop Return to the upper layer from the volume
element.scrollLeft Back to the left from the roll
element.scrollWidth Returns the actual width itself, chromeless
element.scrollHeight Return with their actual height, without borders

scroll scroll events, triggered when the scroll bar

Mouseenter the difference with mouseover

1. First thing in common, both of which are mouse moved to the target position of the trigger event

2.mouseover mouse over the box itself triggers, after the mouse will trigger the sub box, mouseenter only through their own trigger box

3. The reason why there results 2, because mouseenter not bubble

Trigger mouseleave leave the mouse, the same does not bubble

Animation function package

The principle Animation

The core principle: the use of a timer setinternal () constantly moving box position

Implementation steps

1. The current position of the box is obtained

2. Let the box plus a moving distance at the current position

3. Use a timer repeat this operation

4. Add a timer ending condition

5. Note that this positioning element needs to be added in order to use element.style.left

 <style>
       div{
           position:absolute;
           background-color: pink;
           height:100px;
           width:100px;
           
       }
    </style>
</head>
<body>
    <div></div>
    <script>
        var div=document.querySelector('div');
        var timer=setInterval(function() {
            if(div.offsetLeft>=400){//设置停下的条件
                clearInterval(timer);
            }
            div.style.left=div.offsetLeft+1+'px';
        }, 30);
    </script>
</body>

Animation function package

Animation functions to different elements of different recording timer

If multiple elements are animated using this function, every time the timer var statement, we can give different statements of different elements timer (with their own dedicated timer).

The core principle: the use js is a dynamic language, you can easily add a property to the current object.

<body> 
    <Button> motion </ Button> 
    <div> </ div> 
    <Script> var div = document.querySelector ( ' div ' );
         var BTN = document.querySelector ( ' Button ' ); 
        function Animate (obj, target) { // when the continuous click of a button, the speed of movement will be faster, because adding a number of timers
                 // solution, let the elements keep only a timer to clear the timer before, leaving only the current timer                 the clearInterval (obj.timer); 
            obj.timer = the setInterval (function () {
             IF (obj.offsetLeft> = target) { // set the conditions to stop the                 clearInterval (timer);
        
             

 
            } 
            obj.style.left=obj.offsetLeft+1+'px';
        }, 30);
        };
        btn.addEventListener('click',function(){
            animate(div,200);
        });
    </script>
</body>

Easing the principles of animation

Easing animation element is to allow the movement speed vary, the most common is to allow the speed to slow down

Thinking

1. Let the box every time the distance traveled slowly getting smaller, the speed will gradually fall

2. The core algorithm (target value - the current position) / 10 (random number, depending on the desired effect) of each movement as steps

3. Stop conditions: current position equals the target position of the box to stop the timer

Code implementation, the above code simply adding +1 to a progressively smaller value to

4. The need for rounding step value, particularly the easing animation moves between a plurality of targets.

If the step value> 0 is rounded up, a step value <0 rounded down. Such as

var step = (target position - current position) / 10;

step=step>0?math.ceil(step):math.floor(step);

Add animation callback function

Callback: function can be used as a parameter, the function passed as a parameter to another function which, when the function is executed after the finish, then pass in the implementation of this function, this process is called a callback

Callback function to write the location of the end of the timer position

<body> 
    <Button> motion </ Button> 
    <div> </ div> 
    <Script> var div = document.querySelector ( ' div ' );
         var BTN = document.querySelector ( ' Button ' ); 
        function Animate (obj, target, callback) { // when the continuous click of a button, the speed of movement will be faster, because adding a number of timers
                 // solution, let the elements keep only a timer to clear the timer before, only Keep the current timer
                 // the clearInterval (obj.timer); 
            obj.timer = the setInterval (function () {
                 var STEP = (target-obj.offsetLeft) / 10 ; 
                STEP
        
             STEP => 0 ? Math.ceil (STEP): Math.floor (STEP);
             IF (obj.offsetLeft> = target) { // set the conditions to stop 
                the clearInterval (obj.timer);
                 // callback function to write a timing stop position 
                iF (the callback) { // determines whether there is a callback 
                    the callback (); 
                } 
            } 
            obj.style.left = obj.offsetLeft + STEP + ' PX ' ; 
        }, 30 ); 
        }; 
        btn.addEventListener ( ' the Click ' , function () { 
            Animate (div,200,function(){
                alert(22);
            });
        });
    </script>
</body>

Animation functions into a single package file to js

Because after regular use of this function, it can be packaged into a single js file, use the time to refer to the file

<Script src = "where the animation file"> <script>

Effects movable end section

End mobile touch event

Mobile terminal browser compatibility is better, no need to consider before js compatibility issues, while mobile terminal also has its own unique place, such as touch-screen events touch,

touch object represents a touch point may be a finger, a touch pen, a finger touch objects in response to user (or a stylus) on the screen or touch-screen version of the operating

Touch touch event Explanation
touch off When a finger touches a DOM element triggers
touchmove Slide your finger on the trigger when a DOM element
touchEnd Finger on the trigger when you move from a DOM element

Consistent with the use of click, etc.

Touch event object (TouchEvent)

TouchEvent is a class description plane touching finger state (touch screen, a touch pad) changing events, such events used to describe one or more contacts, so that developers can detect an increase in the movement of the contact, the contacts, reducing etc., touchstart, touchmove, touchend have their own objects

Touch List Explanation
touches The touch screen is a list of all the fingers
targetTouches Touch is a list of the current DOM element on finger
changedTouches Finger status has a list of changes, from there to, changes from scratch

Use similar with the web version, function (e) then use

The second is more commonly used, if the want the first information on the finger is being touched, can e.targetTouches [0];

Drag element movable end

1.touchstart  touchmove  touchend可以实现拖动元素

2.拖动元素需要当前手指的坐标值,我们可以使用targettouches里面的pageX与pageY

3.移动端拖动原理:手指移动的时候,计算出手指移动的距离,用盒子原来的位置加上手指移动的距离

4.手指移动的距离:手指滑动时的位置-触摸时的位置

注意:防止屏幕默认的滚动机制

<body>
    <div></div>
    <script>
        var div=document.querySelector('div');
        var startX=0;
        var startY=0;
        var x=0;
        var y=0;
        div.addEventListener('touchstart',function(e){
            startX=e.targetTouches[0].pageX;
            startX=e.targetTouches[0].pageX;
            x=this.offsetLeft;
            y=this.offsetTop;
        });
        div.addEventListener('touchmove',function(e){
            var moveX=e.targetTouches[0].pageX;
            var moveY=e.targetTouches[0].pageY;
            this.style.left=x+moveX+'px';
            this.style.top=y+moveY+'px';
            e.preventDefault();//阻止屏幕滚动的默认行为
        })
    </script>
</body>

classList属性

classlist是HTML5新增的一个属性,可以返回元素的类名

该元素用于在元素中添加,移除以及切换css类

添加类

element.classList.add('类名');如focus.classList.add('current');

删除类

element.classList.remove('类名');

切换类

element.classList.toggle('类名');

有了这个功能后开关灯的案例可以简写为

<button>开关灯</button>
    <script>
        var btn=document.querySelector('button');
        btn.addEventListener('click',function(){
            document.body.classList.toggle('bg');
        })
    </script>

swiper插件的使用

中文官网地址:https://www.swiper.com.cn/

1.引入插件相关文件

去官网下载插件,在下载包里demos里面根据编号找对应的样式,同时还需引入其dist下的css和js

2.按照规定语法使用

本地存储

本地存储特性

1.数据存储在用户浏览器中

2.设置,读取方便,甚至页面刷新都不丢失数据

3.容量较大,sessionStorage容量为5M,localStorage容量为20M

window.sessionStorage

1.生命周期为关闭浏览器窗口

2,在同一个窗口(页面)下数据可以共享

3.以键值对的形式存储使用

存储数据:sessionStorage.setItem(key,value);

获取数据:sessionStorage.getItem(key);

删除数据:sessionStorage.removeItem(key);

删除所有数据:sessionStorage.clear();

 

Guess you like

Origin www.cnblogs.com/echol/p/12570250.html