Last active
August 29, 2015 14:04
-
-
Save jikeytang/d5bfac89c90e85042a8f to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140806-题目1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
用最简短的js原生代码实现一个div拖拽的过程。 | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 {width: 100px; height: 100px; background: red; position: absolute;}
#img1 { position: absolute;}
</style>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
var oImg = document.getElementById('img1');
drag(oImg);
drag(oDiv);
function drag(obj) {
obj.onmousedown = function(ev) {
var ev = ev || event;
var disX = ev.clientX - this.offsetLeft;
var disY = ev.clientY - this.offsetTop;
if ( obj.setCapture ) {
obj.setCapture();
}
document.onmousemove = function(ev) {
var ev = ev || event;
if(ev.clientX<350){
obj.style.left=0;
}else{
obj.style.left = ev.clientX - disX + 'px';
obj.style.top = ev.clientY - disY + 'px';
}
}
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
//释放全局捕获 releaseCapture();
if ( obj.releaseCapture ) {
obj.releaseCapture();
}
}
return false;
}
}
}
</script>
</head>
<body>
<div id="div1"></div>
<img src="1.jpg" id="img1" />
</body>
</html>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
我方法应该是最复杂的