[Tutorial] Cara men-Drag n Drop gambar di browser dengan Javascript
|Shares :

[Tutorial] Cara men-Drag n Drop gambar di browser dengan Javascript


Berikut contoh koding javascript untuk men-drag Gambar di area browser.

buat sebuah file misal contoh.html . masukan kode dibawah ini lalu buka dibrowser.


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
img { position: absolute; }
</style>

<script type='text/javascript'>
window.onload = function() {

  movMeId = document.getElementById("ImgMov");
  movMeId.style.top = "80px";
  movMeId.style.left = "80px";

  document.onmousedown = coordinates;
  document.onmouseup = mouseup;

  function coordinates(e) {
    if (e == null) { e = window.event;}
    
    // e.srcElement holds the target element in IE, whereas e.target holds the target element in Firefox
    // Both properties return the HTML element the event took place on.

    var sender = (typeof( window.event ) != "undefined" ) ? e.srcElement : e.target;

    if (sender.id=="ImgMov") {
      mouseover = true;
      pleft = parseInt(movMeId.style.left);
      ptop = parseInt(movMeId.style.top);
      xcoor = e.clientX;
      ycoor = e.clientY;
      document.onmousemove = moveImage;
      return false;
    } else { 
        return false;
    }
  }

  function moveImage(e) {
    if (e == null) { e = window.event; }
    movMeId.style.left = pleft+e.clientX-xcoor+"px";
    movMeId.style.top = ptop+e.clientY-ycoor+"px";
    return false;
  }

  function mouseup(e) {
    document.onmousemove = null;
  }
}
</script>
</head>

<body>
  <img id="ImgMov" src="http://placehold.it/100x100&text=Contoh Gambar" width="300" height="300" />
  <p>Drag and drop around Gambar.</p>
</body>

</html>

Sumber : Mozilla


Tags : #


SHARES :


Budy K's Avatar

Sains & Teknologi Enthusiast, Software Developer. Check my profile!
> 75% komen akan dibalas. Mohon sabar ya. Simpan halaman ini dan cek kembali lagi

Comments

* Email will not be published


    Privacy .ToS .Contact Us
    © 2017 Teknosains