<概述>JavaScript是一種常用的腳本語言,廣泛運用于Web開發中,其語法簡單易懂,讓開發者可以輕松地實現不同的功能。在這篇文章中,我將為大家帶來一些JavaScript的炫酷例子,這些例子不僅展現了JavaScript的威力,也能在一定程度上讓我們獲得更深的學習體驗。
1. 拖拽效果
let oDiv = document.getElementById('div'); let disX = 0; let disY = 0; oDiv.onmousedown = function (e) { disX = e.clientX - oDiv.offsetLeft; disY = e.clientY - oDiv.offsetTop; document.onmousemove = function (e) { let L = e.clientX - disX; let T = e.clientY - disY; if (L< 0) { L = 0; } else if (L >document.documentElement.clientWidth - oDiv.offsetWidth) { L = document.documentElement.clientWidth - oDiv.offsetWidth; } if (T< 0) { T = 0; } else if (T >document.documentElement.clientHeight - oDiv.offsetHeight) { T = document.documentElement.clientHeight - oDiv.offsetHeight; } oDiv.style.left = L + 'px'; oDiv.style.top = T + 'px'; } } document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }
2. 計算器
let num1; let num2; let operator; let showBox = document.getElementById('show-box'); function inputNum(n) { if (showBox.value == '0') { showBox.value = n; } else { showBox.value += n; } } function clearData() { showBox.value = '0'; } function setOperator(op) { operator = op; if (!num1) { num1 = Number(showBox.value); showBox.value = ''; } else { num2 = Number(showBox.value); calculate(); } } function calculate() { switch (operator) { case '+': showBox.value = num1 + num2; break; case '-': showBox.value = num1 - num2; break; case '*': showBox.value = num1 * num2; break; case '/': showBox.value = num1 / num2; break; } num1 = Number(showBox.value); showBox.value = ''; }
3. 時鐘效果
function showTime() { let timeBox = document.getElementById('time-box'); let now = new Date(); let h = now.getHours().toString().padStart(2, '0'); let m = now.getMinutes().toString().padStart(2, '0'); let s = now.getSeconds().toString().padStart(2, '0'); timeBox.innerHTML = `${h}:${m}:${s}`; } setInterval(showTime, 1000);
4. 輪播圖
let imgs = [ 'img/1.jpg', 'img/2.jpg', 'img/3.jpg', 'img/4.jpg' ]; let index = 0; let imgBox = document.getElementById('img-box'); function showImg() { imgBox.style.backgroundImage = `url(${imgs[index]})`; index ++; if (index === imgs.length) { index = 0; } } setInterval(showImg, 3000);<結論>以上例子展示了JavaScript的強大功能,通過JavaScript,我們可以輕松實現拖拽、計算器、時鐘、輪播圖等多種功能。在開發中,我們可以運用這種能力,為用戶提供更好的體驗和更多的交互。雖然JavaScript并不是一種完美的語言,但它的優點足以抵消缺點,讓開發者輕松應對各類工作。
上一篇css圓環帶動畫