如何用 JavaScript 在浏览器中弹窗 如何在 JavaScript 中制作鼠标滑过按钮改变背景颜色 如何在 JS 中点击按钮使数字增加 如何在 JS 中循环打印多少次
HTML
<! DOCTYPE html >
< html lang = " en" >
< head> < meta charset = " UTF-8" > < title> JS Lab</ title> < link rel = " stylesheet" href = " css/style.css" >
</ head>
< body> < button class = " btn" onclick = " alertBtn ( ) " > Alert Button</ button> < hr> < button class = " btn" id = " hoverButton" > Hover Button</ button> < hr> < button class = " btn" id = " increaseButton" > Incrementing Button</ button> < span id = " number" class = " even" > 0</ span> < hr> < p class = " p-loop" > For Loops: Print "Hello!" 10 times</ p> < div id = " container" > </ div>
</ body>
< script async src = " js/lab.js" > </ script>
</ html>
CSS
body { font-family : Arial; font-size : 16px; }
hr { border : 1px dashed #ddd; }
.btn { padding : 8px 20px; margin : 5px 0; border-radius : 100px; border : 1px solid #aaa; }
.btn:hover { background : #fff; }
#hoverButton { background : green; color : #fff; border : 0; }
#number { font-size : 20px; margin-left : 15px; }
.p-loop { font-weight : bold; }
.odd { color : blue; }
.even { color : red; }
JavaScript
function alertBtn ( ) { alert ( "Hello world!" ) ;
}
let hoverButton = document. getElementById ( 'hoverButton' ) ;
hoverButton. onmouseover = function ( ) { this . style. backgroundColor = 'orange' ;
} ;
hoverButton. onmouseout = function ( ) { this . style. backgroundColor = '' ;
} ;
document. getElementById ( 'increaseButton' ) . addEventListener ( 'click' , function ( ) { let numberElement = document. getElementById ( 'number' ) ; let currentNumber = parseInt ( numberElement. textContent, 10 ) ; currentNumber += 1 ; let newClass = currentNumber % 2 === 0 ? 'even' : 'odd' ; numberElement. textContent = currentNumber; numberElement. className = newClass;
} ) ;
for ( let i = 0 ; i < 10 ; i = i + 1 ) { document. getElementById ( 'container' ) . append ( 'Hello! ' ) ;
}
function changeFontColor ( ) { let changeButton = document. getElementById ( "pColor" ) ; let color = changeButton. style. color; if ( color == "red" ) { changeButton. style. color = 'blue' ; } else { changeButton. style. color = 'red' ; }
}