Javascript allows you to drag images with the mouse and be compatible with mainstream browsers such as IE, FF, Firefox, and Google.

Source: Internet
Author: User

Note: Use preventDefault to prevent default browser event operations.
Copy codeThe Code is as follows:
<Script language = "javascript" type = "text/javascript">
Var isDrag = false;
Function isIE (){
If (navigator. userAgent. indexOf ("MSIE")> 0) {return true ;}
Else {return false ;}
}
Function addListener (element, e, fn ){
If (isIE () {element. attachEvent ("on" + e, fn );}
Else {element. addEventListener (e, fn, false );}
}
Function drag (e ){
Var e = e | window. event;
Var element = e. srcElement | e.tar get;
If (e. preventDefault) e. preventDefault ();
Else e. returnvalue = false;
IsDrag = true;
Var relLeft = e. clientX-parseInt (element. style. left );
Var relTop = e. clientY-parseInt (element. style. top );
Element. onmouseup = function () {isDrag = false ;}
Document. onmousemove = function (e_move ){
Var e_move = e_move | window. event;
If (isDrag ){
Element. style. left = e_move.clientX-relLeft + "px ";
Element. style. top = e_move.clientY-relTop + "px ";
Return false;
}
}
}
Window. onload = function ()
{
Var element = document. getElementById ("elimg ");
Var element2 = document. getElementById ("eldiv ");
AddListener (element, "mousedown", drag );
AddListener (element2, "mousedown", drag );
}
</Script>
<Div id = "eldiv" style = "width: 140px; height: 100px; background: # EEE; position: absolute; left: 117px; top: 124px"> </div>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.