javascript, jQuery & Node.js
javascript 간단한 event / 버튼클릭 마우스오버 alert / 클릭하면 random값 / 자바스크립트로 style 변경하기
yy_dd2
2021. 3. 10. 17:06
반응형
![]() |
![]() |
![]() |
버튼 클릭하면 alert 나오게하는건
<button onclick="alert('클릭해주셔서 감사합니다');">클릭해주세요</button>
이렇게 할수있지만 올바른 방법이 아니라고 배웠던거 같다
간단하게 마우스오버와 아웃 속성을 이용해서 스타일 바꿀수있다
<div onmouseover="this.style.backgroundColor = 'red';
this.style.borderRadius = '30px';"
onmouseout="this.style.backgroundColor = '';
this.style.borderRadius = '';
"></div>
여기서 style에 적을때는 background-color 라고 적지만 -를 사용하지 못하니
backgroundColor라고 C대문자로 사용한다
클릭하면 이벤트가 실행된다
<div onclick="clickdHandler(this)"></div>
스크립트에
<script type="text/javascript">
function clickdHandler(v) {
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
v.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
}
</script>
이렇게 작성하고 클릭하면 박스안의 색이 바뀌도록했다
그리고 테두리도 해줬다 다른색 나오라고 값을 한번 더 돌렸다
<script type="text/javascript">
function clickdHandler(v) {
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
v.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
if (v.style.backgroundColor){
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
v.style.border = `3px solid rgb(${r},${g},${b})`;
}
}
</script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
button { width:100px; height: 50px;}
div {background-color: bisque; width: 100px; height: 50px; border: 1px solid deepskyblue;text-align: center; font-size: 15px;}
</style>
<script type="text/javascript">
function clickdHandler(v) {
var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);
v.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
if (v.style.backgroundColor){
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
v.style.border = `3px solid rgb(${r},${g},${b})`;
}
}
</script>
</head>
<body>
<button onclick="alert('클릭해주셔서 감사합니다');">클릭해주세요</button>
<br><br>
<div onmouseover="this.style.backgroundColor = 'red';
this.style.borderRadius = '30px';"
onmouseout="this.style.backgroundColor = '';
this.style.borderRadius = '';
"></div>
<br><br>
<div onclick="clickdHandler(this)"></div>
</body>
</html>
반응형