js基礎-函式
阿新 • • 發佈:2021-12-12
函式
1.函式的概念:把一段需要重複使用的程式碼,用function語法包起來,方便使用。
2.函式的宣告:
<1>具名函式 :function 變數名(){}
<2>匿名函式 :var func = function(){};
<3>ES6箭頭函式 :()=>{}
3.函式的呼叫:
<1>名字(); 函式可以多次呼叫
<2>在事件中呼叫
4.匿名函式自呼叫:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> </body> </html> <script> //具名函式 function aaa() { console.log('我是函式1') } //匿名函式 aaa() var bbb=function () { console.log('匿名函式') } bbb() //匿名函式自呼叫 ;function f() { console.log('匿名函式自呼叫') } () </script>
5.函式返回值:
<1>所有函式都會有函式返回值即函式執行後一定會返回一個結果,如果沒有定義預設返回undefined;
<2>在函式中,return後定義返回值;
<3>在函式中,return之後的程式碼就不會再執行了
<4>return只能用於函式中,用在其他地方會報錯
6.封裝:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"><title>Title</title> <style> body{ margin: 0; } #div1{ width: 100px; height: 100px; background: red; position: absolute; left: 0; top: 0; } #div2{ width: 100px; height: 100px; background: green; position: absolute; left: 500px; top: 200px; } </style> </head> <body> <div id="div1"></div> <div id="div2"></div> </body> </html> <script> const div1=document.getElementById('div1') const div2=document.getElementById('div2') function crash(obj1,obj2) { if (obj1.offsetLeft+obj1.offsetWidth<obj2.offsetLeft|| obj2.offsetLeft+obj2.offsetWidth<obj1.offsetLeft|| obj1.offsetTop+obj1.offsetHeight<obj2.offsetTop|| obj2.offsetTop+obj2.offsetHeight<obj1.offsetTop ){ div2.style.background='' }else{ div2.style.background='black' } } function move(obj){ obj.onmousedown=function (event) { const chaX=event.clientX-obj.offsetLeft const chaY=event.clientY-obj.offsetTop document.onmousemove=function (event) { obj.style.left=event.clientX-chaX+'px' obj.style.top=event.clientY-chaY+'px' crash(div1,div2) } document.onmouseup=function () { document.onmousemove=null } } } move(div1) move(div2) </script>