๐ป๋ฐ์ค ์ฌ์ด์ฆ ์กฐ์ ํ๊ธฐ๐ป
์ฐ์ธกํ๋จ๋ถ๋ฅผ ํด๋ฆญํ๊ณ ๋๋๊ทธ๋ฅผ ํ์ ๋, ๋ถํฌ๋ช ๋๊ฐ ๋ฎ์์ง๊ณ ๋ง์ฐ์ค ์์น๋งํผ ๋ฐ์ค ์ฌ์ด์ฆ๊ฐ ์กฐ์ ๋๋ค.
๊ธฐ๋ณธ ๋ผ๋
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 150px;
height: 150px;
background-color: gold;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="box1" class="box"></div>
</body>
</html>
์ฐ์ธกํ๋จ๋ถ ๋๋ฌ ์ฌ์ด์ฆ ์กฐ์ ํ๊ธฐ
๋ง์ฐ์ค๊ฐ ์์์ ์ฐ์ธก ํ๋จ๋ถ๋ฅผ ๋๋ ๋์ง ํ์ธํ๋ ํจ์๋ฅผ ๋ง๋ ๋ค.
function isVaild(event) {
//1. ํ์ฌ ์์์ ํฌ๊ธฐ ํ์ธ
let w = parseInt(window.getComputedStyle(box1).width);
let h = parseInt(window.getComputedStyle(box1).height);
//2. ์์ width, height์์ 10px ์์ชฝ ์์ญ์ธ์ง ํ์ธ
if (event.offsetX >= (w-10) && event.offsetX <= w
&& event.offsetY >= (h-10) && event.offsetY <= h) {
return true;
}
return false;
}
์ด๋ฒคํธ
<script>
const box1 = document.getElementById('box1');
let isDown=false;
window.onmousedown = function() {
// ๋น ํ๋ฉด์ด ์๋ box๋ฅผ ์ ํํ์ ๋
if (event.target.id == 'box1' && isVaild(event)) {
isDown = true;
box1.style.opacity = .3;
}
};
function isVaild(event) {
//๋ง์ฐ์ค๊ฐ ์์์ ์ฐ์ธก ํ๋จ๋ถ๋ฅผ ๋๋ ๋์ง ํ์ธ
//1. ํ์ฌ ์์์ ํฌ๊ธฐ ํ์ธ
let w = parseInt(window.getComputedStyle(box1).width);
let h = parseInt(window.getComputedStyle(box1).height);
//2. ์์ width, height์์ 10px ์์ชฝ ์์ญ์ธ์ง ํ์ธ
if (event.offsetX >= (w-10) && event.offsetX <= w
&& event.offsetY >= (h-10) && event.offsetY <= h) {
return true;
}
return false;
}
window.onmousemove = function() {
if (isDown){
box1.style.width = event.clientX + 'px';
box1.style.height = event.clientY + 'px';
}
};
window.onmouseup = function() {
isDown = false;
box1.style.opacity = 1;
};
</script>
'WEB > JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JavaScript] ํด๋ฆญ ์ด๋ฒคํธ : ๋ฐ์ํ ๋ฉ๋ด๋ฐ ๋ง๋ค๊ธฐ (0) | 2023.10.12 |
---|---|
[JavaScript] CSS ์กฐ์ - transition ์ถ๊ฐ (0) | 2023.10.12 |
[JavaScript] ๋๋๊ทธ์ฑ๋๋กญ ์ด๋ฒคํธ : ์์ ์ฌ๋ฌ๊ฐ Drag & Drop (0) | 2023.10.12 |
[JavaScript] ๋๋๊ทธ์ค๋๋กญ ์ด๋ฒคํธ : ์์ 1๊ฐ Drag & Drop (0) | 2023.10.12 |
[JavaScript] ํด๋ฆญ ์ด๋ฒคํธ : ํด๋ฆญํ ์์น์ ์์ ์์ฑํ๊ธฐ (0) | 2023.10.12 |