preface

Let’s jump right into WebApi and skip the basics of THE JS syntax.

The body of the

native

Various selectors
<p class='clsP' id='idP2'>< span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 13px! Important; white-space: normal; = document. GetElementsByClassName (' clsP) returns an array the let / / tag selector pEls = ul. The getElementsByTagName (" p ") / / returns the first matching to the first element of the id Label let firstclsP = document. QuerySelector (' clsP ') / / return all let allP = document. QuerySelectorAll (". ClsP ") < / script >Copy the code
Native click event
<script> let BTN = document.getelementbyid (' BTN ') btn.onclick = function () {console.log(' click ')} btn.addEventListener('click',function () { console.log('addEventListener') }) </script>Copy the code
InnerHtml and the innerText
<div>< p> 123 < SPN >456</ SPN ></ p> <div id="divId"></div> <script  document.querySelector('div') div.innerHTML = '<del>123</del>' let textDiv = document.getElementById('divId') textDiv.innerText = '<del>123</del>' </script> </body>Copy the code
Manipulate element attributes
<img SRC ="images/ldh. JPG "Alt ="" width="100" > <img SRC ="images/ldh. JPG" Alt ="" width="100" height="100"> <script> let ldh = document.getElementById('ldh') let zxy = document.getElementById('zxy') let img = document.querySelector('img') ldh.onclick = function () { img.src = 'images/ldh.jpg' } zxy.onclick = function () { img.src = 'images/zxy.jpg' } </script> </body>Copy the code
Operating style
    <div></div>
    <script>
      let div =  document.querySelector('div')
        div.onclick = function () {
            div.style.backgroundColor = 'red'
            div.style.width = '100px'
            div.style.height = '100px'
        }
    </script>
</body>
Copy the code
Changing the class style
    <div class="first">

    </div>
    <script>
       let div = document.querySelector('.first')
        div.onclick =  function () {
            this.className = 'first second'
        }
    </script>
</body>
Copy the code
Custom properties
    <div class="demo1" index="1" id="nav"></div>
    <script>
       let div = document.querySelector('div')
        console.log(div.getAttribute('class'))
        console.log(div.getAttribute('index'))
        div.setAttribute('index',2)
        console.log(div.getAttribute('index'))
    </script>
</body>
Copy the code
The parent node
<body> <div class="demo"> <div class="box"> <span class="erweima">x</span> </div> </div> <script> let span = Document.queryselector ('.erweima') // This element finds its direct parent console.log(span.parentelement) </script> </body>Copy the code
Child nodes
<! - node advantages -- -- > < div > I am a div < / div > < span > I am span < / span > < ul > < li > I am li < / li > < li > I am li < / li > < li > I am li < / li > < li > I am li < / li > < / ul > Li < ol > < li > I < / li > < li > I am li < / li > < li > I am li < / li > < li > I am li < / li > < / ol > < div class = "demo" > < div class = "box" > < span Class ="erweima"> </div> </div> <script> var ul = document.querySelector('ul'); var lis = ul.querySelectorAll('li'); All childNodes include element nodes, text nodes, and so on, including that newline space, so 9. console.log(ul.childNodes); console.log(ul.childNodes[0].nodeType); console.log(ul.childNodes[1].nodeType); // 2. Children get all the child element nodes, which is the common console. Log (ul. </script> </body>Copy the code
Brother nodes
<div> let divEle = document.querySelector('div') // This node contains Spaces and newlines Console.log (divele.previousSibling) console.log(divele.nextsibling) // This is the element, Development with the console. The log (divEle. PreviousElementSibling) console. The log (divEle. NextElementSibling) < / script > < / body >Copy the code
Remove nodes
</li> <li>1</li> 2</li> </li> </li> </li> </li> </li> </li> </li> </li> </li> </li> </li> </li> </li> <script> let button = document.querySelector('button') let ulEle = document.querySelector('ul') button.onclick = function () { if(ulEle.children.length === 0) { this.disabled = true } else { ulEle.removeChild(ulEle.children[0]) } } </script> </body>Copy the code
Create a node
</body> <script> let nowDate = new Date() let bodyEl = document.querySelector('body') for (let I = 0;  i < 1000; i++) { let div = document.createElement('div') div.style.width = '100px' div.style.height = '2px' div.style.border = '1px solid red' bodyEl.append(div) } console.log(new Date()-nowDate) </script>Copy the code
Removing listening Events
< button > listening 1 < / button > < button > listen 2 < / button > < script > = document. The buttons let querySelectorAll (" button ") [0] buttons. The onclick = function () {alert('123') buttons[0].onclick = null} buttons[1].addEventListener('click',fn) function fn() { alert(222) buttons[1].removeEventListener('click',fn) } </script> </body>Copy the code
The event object
<div>123</div> <ul> <li>123</li> <li>456</li> <li>789</li> </ul> <script> let divEl = document.querySelector('div') let ulEl = document.querySelector('ul') divEl.addEventListener('click',function (e) { console.log(this) Console.log (e.t. get)}) // e.t. get refers to which element to click on, Ulex.addeventlistener ('click',function (e) {console.log(this) console.log(e.currentTarget) console.log(e.target) }) </script> </body>Copy the code
Prevent event bubbling
<div class="father"> <div class="son"></div> </div> <script> let divFather = document.querySelector('.father') let DivSon = Document.querySelector ('.son') Divson.addeventListener ('click',function (e) {e.topPropagation () console.log('son') }) divFather.addEventListener('click',function (e) { console.log('father') }) </script> </body>Copy the code
coordinates
    <script>
        document.addEventListener('click',function (e) {
            console.log(e.clientX)
            console.log(e.clientY)
            console.log('--------')
            console.log(e.pageX)
            console.log(e.pageY)
            console.log('--------')
            console.log(e.screenX)
            console.log(e.screenY)
        })
    </script>
</body>
Copy the code

ScreenX: The mouse position is relative to the horizontal offset of the user’s screen. ScreenY is vertical, and the reference point is the upper left corner of the screen.

ClientX: In contrast to screenX, the reference point is changed to the top left corner of the browser content area. The reference point moves as the scroll bar moves.

PageX: The reference point is also the top left corner of the browser’s content area, but it doesn’t change with the scroll bar

Mouse events
< script > document. AddEventListener (' keyup ', function (e) {the console. The log (' keyboard up ')}) Document. The addEventListener (' keypress ', function (e) {the console. The log (' button press, Not identification function keys such as CTRL shift ')}) document. The addEventListener (' keydown ', function (e) {the console. The log (' button press, </script> </body>Copy the code
The Window object
<body> <script> window.onload = function () {console.log(' Page element loading completed, // Listen to the browser window size change <body> <div></div> <script> window.onload = function () {let divEl = document.querySelector('div') window.addEventListener('resize',function () { console.log(window.innerWidth) If (window.innerwidth < 800){divel.style. display = 'none'}})} </script> </body> <script> function Callback () {console.log('1111')} window.setTimeout(callback,3000) </script> </body> <script> SetInterval (function () {console.log('111')},100) </script> </body> // window.location <body> <button> < script > let buttonEl = document. QuerySelector (' button) buttonEl. AddEventListener (' click ', function () {back / / / / no history Location.replace ('https://www.baidu.com') // location.reload() // Record history back // location.assign('https://www.baidu.com')}) </script> </body>Copy the code
Offset series
<div class="father"> <div class="son"></div> </div> <div class="w"></div> <script> let fatherDiv = document.querySelector('.father') let sonDiv = document.querySelector('.son') console.log(fatherDiv.offsetTop) Console.log (fatherdiv.offsetLeft) If not found body console.log(sondiv.offsetLeft) let wDiv = document.querySelector('.w') console.log(wdiv.offsetwidth) Console.log (sondiv.offsetParent) console.log(sondiv.offsetparent) console.log(sondiv.offsetparent) Log (sondiv.parentnode) </script> </body>Copy the code

In this case, the offsetlet is the distance from its left margin to the left margin of the parent element

“OffsetWidth” and “style.width” have no units or px units

Series of clien
Let divEl = document.querySelector('div') console.log(divEl.offsetWidth) console.log(divEl.clientWidth) </script> </body>Copy the code
Immediate execution function
< script > (function (a, b) {the console. The log (a + b)}) (1, 2) < / script > < / body >Copy the code
Scroll series
<div style = "box-sizing: border-box; color: RGB (50, 50, 50); font-size: 14px! Important; word-break: inherit! Important; </div> <script> let divEl = document.querySelector('div') // Display the scroll bar, Console. log(divel.scrollHeight) console.log(divel.clientheight) console.log(divel.clientheight) Console.log (this.scrolltop)}) </script>  </body>Copy the code
Mouse into away event
<div class="father"> <div class="son"></div> </div> <script> let fatherEl = document.querySelector('.father') let sonEl = document.querySelector('.son') // MouseEnter does not bubble events, Move to the don't trigger word elements Also to use mouseleave fatherEl. AddEventListener (" mouseenter ", function (e) {the console. The log (' fatherElmouseenter ')}) fatherEl.addEventListener('mouseover',function (e) { console.log('fatherElmouseover') }) </script> </body>Copy the code
Mobile touch event
<div></div> <script> let divEl = document.querySelector('div') let startx = 0 let starty = 0 = 0 divEl.addEventListener('touchstart', function (e) { console.log(e.targetTouches[0].pageX) console.log(e.targetTouches[0].pageY) startx = e.targetTouches[0].pageX starty = e.targetTouches[0].pageY x = this.offsetLeft y = this.offsetTop }) divEl.addEventListener('touchend', function (e) { console.log(e) }) divEl.addEventListener('touchmove', function (e) { let moveX = e.targetTouches[0].pageX-startx let moveY = e.targetTouches[0].pageY - starty divEl.style.left = x +moveX + 'px' divEl.style.top = y+ moveY+ 'px' e.preventDefault() }) </script> </body>Copy the code
storage
<input id="name" type="text" placeholder=" password" > <input type="radio" class="storage" name="storage" checked="true" value="1">localStorage <input type="radio" class="storage" name="storage" Value = "2" > sessionStorage < button > save < / button > < script > let radioEls = document. QuerySelectorAll (' storage ') let inputName  = document.getElementById('name') let inputPassword = document.getElementById('password') let buttonEl = document.querySelector('button') let storageType = 1 for (let i = 0; i < radioEls.length; i++) { radioEls[i].addEventListener('change', Function (e) {storageType = this.value})} Unless your manual cleaning buttonEl. AddEventListener (' click ', function () { let name = inputName.value let password = inputPassword.value if (storageType === 1) { localStorage.setItem('name',name) localStorage.setItem('password',password) } else { sessionStorage.setItem('name',name)  sessionStorage.setItem('password',password) } }) </script> </body>Copy the code

Jquery (Zepto recommended for mobile Web)

Various selectors
$(function () {$(' nav ') $(' ul li) $(' ul li: first) $(' ul li: eq. (2)) $(' ol li: even) $(' ol li: odd ') / / sibling elements $(' ol . The item '). Siblings (' li ') console. The log ($(' son '). The parent ()) / / son $(' nav '). The children (" p "). The CSS (" color ", "red") / / all the p tag Similar to the descendant selectors $(' nav '), find (" p "). The CSS (' color ', 'orange') / / chain programming $(this).css('background-color','').siblings('button').css('background-color','red') }) </script>Copy the code
Css styles
        $('div').css({
            width:400,
            height:400,
            backgroundColor:'blue'
        })
        
        $(this).css('background-color','')
    	
    	$(this).toggleClass('current')
    
    	$(this).addClass('current').siblings('li').removeClass('current')
    	let indexs = $(this).index()
        $('.item').eq(indexs).show().siblings('.item').hide()
})
Copy the code
animation
        $('button').click(function () {
            $('div').animate({
                left:500,
                top:300,
                width:400,
                opacity:.4
            },3000)
        })
 $('.back').fadeIn()
 $('.back').fadeOut()
</script>
Copy the code
Attribute operation
$(' a '). Prop (' title ', 'we are both good') / / to get custom attributes console. The log ($(' div '). Attr (' index '))Copy the code
The text content
    console.log($('div').html())
    console.log($('div').text())
    console.log($('input').val())
    $('input').val('123')
</script>
Copy the code
Return ancestral elements
<div class="one"> <div class="two"> <div class="three"> <div class="four"> <div class="three"> <div class="four"> console.log($('.four').parent().parent().parent()) console.log($('.four').parents()) console.log($('.four').parents('.two')) </script> </body>Copy the code
Traverse elements
<div>1</div>
<div>2</div>
<div>3</div>
<script>
    $(function () {
        let sum = 0;
        let arr = ['red','orange','blue']
        $('div').each(function (i,el) {
            $(el).css('color',arr[i])
            sum+=parseInt($(el).text())
        })
        console.log(sum)
    })
</script>
</body>
Copy the code
Delete add element
< ul > < li > original li < / li > < / ul > < div class = "test" > I am the original div < / div > < script > $(function () {let li = $(' < li > I am later to create < / li > ') $(' ul '). Append (li) let lis = $(' < li > I < / li > 'on it) $(' ul'). The prepend (lis) let div = $(' < div > I was born a stepmother < / div > ') The '$(') before (div) / / delete/remove elements / / find / $(' ul'). The remove () / / delete child elements $(' ul '). The empty ()}) < / script > < / body >Copy the code
Get element size
<div>< script> $(function () {// 1.width ()/height()} console.log($('div').width()) // 2. Console. log($('div').innerWidth()) // 3.outerWidth () / Console.log ($('div').outerWidth()) // 4.outerWidth (true) / $('div').outerwidth (true))}) </script> </body>Copy the code
Element position
<div class="father"> <div class="son">< div class="son">< div class="son" Console. The log ($(' son '). The offset ()) / / to get from the location of the positioning element. The console log ($(' son '). The position ()}) < / script > < / body >Copy the code
The event
$(function () { $('div').on('mouseenter mouseleave',function () { $(this).toggleClass('current') }) // $('ul'). On ('click','li',function () {alert(11)}) let li = $('<li> </li>') $('ul').append(li) }) </script>Copy the code
Event unbundling
The < div > < / div > < ul > < li > we are all good children < / li > < li > we are all good children < / li > < li > we are all good children < / li > < / ul > < / p > < p > I am a fart < script > $(function () { $('div').on({ click:function () { console.log(111) }, mouseenter:function () { console.log(222) } }) $('div').off('click') }) </script> </body>Copy the code
Automatically triggered event
<div></div> <input type="text"> <script> $(function () { $('div').on('click',function () { alert(11) }) // I think the main difference here is that triggerHandler prevents event bubbling, $('div').trigger('click') $('div').triggerHandler('click')}) </script>Copy the code
The event object
$(function() {$(document).on("click", function() {console.log(" click"); }) $("div").on("click", function(event) { // console.log(event); Console. log(" clicked div"); Event.stoppropagation (); }) }) </script>Copy the code

conclusion

Finished, the next vUE foundation!!