今天來做一個簡單的拖動效果的案例!!
具體實作功能效果如下所示:
要想做好這個案例首先分為三個部分:html 框架和 css 樣式、JavaScript 的互動效果(點擊彈出和關閉的隱藏效果、最后就是一個拖動的效果)!
首先就是html框架和css渲染的樣式
html框架:
<div class="w"><a href="javascript:;">點擊,彈出登錄框</a></div>
<div class="box">
<div class="first">登錄會員</div>
<a href="JavaScript:;" class="close">關閉</a>
<div class="second">
<label for="">用戶名:</label>
<input type="text" name="" id="" value="請輸入用戶名">
</div>
<div class="second">
<label for="">登錄密碼:</label>
<input type="text" name="" id="" value="請輸入登錄密碼">
</div>
<div class="last">登錄會員</div>
</div>
<div class="bc"></div>
效果如圖所示:

要更好看當然得需要我們的css來渲染頁面:
<style>
* {
margin: 0;
padding: 0;
}
.bc {
background-color: #999;
width: 100%;
height: 100%;
position: fixed;
z-index: -1;
/* display: none; */
}
.w {
position: absolute;
top: 10px;
left: 50%;
transform: translate(-50%);
}
.w>a {
font-size: 20px;
text-decoration: none;
color: black;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
width: 400px;
/* display: none; */
}
.first {
height: 50px;
text-align: center;
line-height: 50px;
}
.second {
margin-right: 40px;
}
.second {
text-align: right;
}
.second>input {
width: 260px;
height: 20px;
margin-bottom: 20px;
outline: none;
border: 1px solid rgb(206, 203, 203);
color: #999;
font-size: 12px;
}
.second>label {
font-size: 13px;
}
.last {
position: relative;
left: 50%;
transform: translate(-50%);
text-align: center;
width: 200px;
height: 35px;
line-height: 35px;
margin-bottom: 30px;
margin-top: 5px;
border: 1px solid rgb(206, 203, 203);
}
.box a {
position: absolute;
right: -20px;
top: -20px;
background-color: #fff;
display: inline-block;
padding: 5px;
height: 26px;
line-height: 26px;
border-radius: 50%;
text-decoration: none;
color: black;
font-size: 13px;
}
</style>
選然后的效果如圖所示:

現在基本框架計已經搭好了,接下來就是我們的 JavaScript 來做的頁面互動效果,可分為兩部來做!
1、點擊彈出和關閉的顯示隱藏效果
<script>
var w = document.querySelector('.w');
var close = document.querySelector('.close');
var box = document.querySelector('.box');
var bc = document.querySelector('.bc');
var first = document.querySelector('.first');
w.addEventListener('click', function () {
bc.style.display = 'block';
box.style.display = 'block';
})
close.addEventListener('click', function () {
bc.style.display = 'none';
box.style.display = 'none';
})
</script>
先把需要點擊或者要變化的元素節點獲取過來,然后再添加點擊事件實作隱藏好顯示的效果!
2、拖動效果
<script>
first.onmousedown = function (e) {
document.documentElement.style.cursor = 'move'
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
document.addEventListener('mousemove', move)
function move(e) {
box.style.left = e.pageX - x + 'px';
box.style.top = e.pageY - y + 'px';
}
document.addEventListener('mouseup', function () {
document.documentElement.style.cursor = 'default';
document.removeEventListener('mousemove', move);
})
}
</script>
緊接著就是一個滑鼠 按下、移動和彈起 的效果,這樣就一氣呵成的實作了我們想要的拖動效果!

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/349654.html
標籤:其他

