纯生JS图片拖拽
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>RunJS</title>
</head>
<body>
<div id="div1"></div>
<img src="http://sandbox.runjs.cn/uploads/rs/198/kn8pai72/index_29.jpg" id="img1" />
</body>
</html>[code]
css
[code]#div1 {width: 100px; height: 100px; background: red; position: absolute;}
#img1 { position: absolute;}js
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;
document.onmousemove = function(ev) {
var ev = ev || event;
obj.style.left = ev.clientX - disX + 'px';
obj.style.top = ev.clientY - disY + 'px';
}
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
}
return false;
}
}
}原文 http://runjs.cn/detail/nivygth7js如何给标签添加一个自定义属性
可以用setAttribute来设定
var img = document.getElementsByTagName("img")[0];
img.setAttribute("zidingyi","bcd");用js给一个DIV一个ID 添加ID
var div = document.getElementsByTagName("div")[0];
div.setAttribute("id","yourdiv");简单拖曵原理实例
<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>简单拖曵原理实例</title>
<style type="text/css">
#drag{width:400px;height:300px;background:url(http://upload.yxgz.cn/uploadfile/2009/0513/20090513052611873.jpg);cursor:move;position:absolute;top:100px;left:100px;border:solid 1px #ccc;}
h2{color:#fff;background: none repeat scroll 0 0 rgba(16, 90, 31, 0.7);color:#FFFFFF;height:40px;line-height:40px;margin:0;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
/*--------------拖曳效果----------------
*原理:标记拖曳状态dragging ,坐标位置iX, iY
* mousedown:fn(){dragging = true, 记录起始坐标位置,设置鼠标捕获}
* mouseover:fn(){判断如果dragging = true, 则当前坐标位置 - 记录起始坐标位置,绝对定位的元素获得差值}
* mouseup:fn(){dragging = false, 释放鼠标捕获,防止冒泡}
*/
var dragging = false;
var iX, iY;
$("#drag").mousedown(function(e) {
dragging = true;
iX = e.clientX - this.offsetLeft;
iY = e.clientY - this.offsetTop;
this.setCapture && this.setCapture();
return false;
});
document.onmousemove = function(e) {
if (dragging) {
var e = e || window.event;
var oX = e.clientX - iX;
var oY = e.clientY - iY;
$("#drag").css({"left":oX + "px", "top":oY + "px"});
return false;
}
};
$(document).mouseup(function(e) {
dragging = false;
$("#drag")[0].releaseCapture();
e.cancelBubble = true;
})
})
</script>
</head>
<body>
<div id="drag">
<h2>来拖动我啊</h2>
</div>
</body>
</html>js如何禁用鼠标右键
function stop(){
return false;
}
document.oncontextmenu=stop;
js拖动窗口
jq版,鼠标拖拽