js實現(xiàn)小窗口拖拽效果
更新時間:2016年12月03日 10:27:00 作者:代碼小公主
這篇文章主要為大家詳細介紹了js實現(xiàn)小窗口拖拽效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了js實現(xiàn)窗口拖拽的具體代碼,供大家參考,具體內(nèi)容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box {
height: 300px;
width: 300px;
background-color: green;
position: absolute;
}
</style>
</head>
<body>
<div id="box">
</div>
</body>
<script type="text/javascript">
var box = document.getElementById("box");
//鼠標按下的函數(shù)
box.onmousedown = function(ev) {
var oEvent = ev || event;
//求出鼠標和box的位置差值
var x = oEvent.clientX - box.offsetLeft;
var y = oEvent.clientY - box.offsetTop;
//鼠標移動的函數(shù)
//把事件加在document上,解決因為鼠標移動太快時,
//鼠標超過box后就沒有了拖拽的效果的問題
document.onmousemove = function(ev) {
var oEvent = ev || event;
//保證拖拽框一直保持在瀏覽器窗口內(nèi)部,不能被拖出的瀏覽器窗口的范圍
var l = oEvent.clientX - x;
var t = oEvent.clientY - y;
if(l < 0) {
l = 0;
} else if(l > document.documentElement.clientWidth - box.offsetWidth) {
l = document.documentElement.clientWidth - box.offsetWidth;
}
if(t < 0) {
t = 0;
} else if(t > document.documentElement.clientHeight - box.offsetHeight) {
t = document.documentElement.clientHeight - box.offsetHeight;
}
box.style.left = l + "px";
box.style.top = t + "px";
}
//鼠標抬起的函數(shù)
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
//火狐瀏覽器在拖拽空div時會出現(xiàn)bug
//return false阻止默認事件,解決火狐的bug
return false;
}
</script>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JS實現(xiàn)鍵值對遍歷json數(shù)組功能示例
這篇文章主要介紹了JS實現(xiàn)鍵值對遍歷json數(shù)組功能,結(jié)合實例形式分析了javascript遍歷json數(shù)組相關(guān)操作技巧,需要的朋友可以參考下2018-05-05
JavaScript實現(xiàn)一個帶AI的井字棋游戲源碼
這篇文章主要介紹了基于JavaScript實現(xiàn)一個帶AI的井字棋游戲源碼,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-05-05
Javascript 函數(shù)中的參數(shù)使用分析
關(guān)于JS中的函數(shù),相信大家已經(jīng)很了解了,其中有些特性呢,感覺還是值得提一提的,下面就說說JS中的函數(shù)吧。2010-03-03
javascript 中null和undefined區(qū)分和比較
這篇文章主要介紹了javascript 中null和undefined區(qū)分和比較的相關(guān)資料,需要的朋友可以參考下2017-04-04

