Accueil > Forum > > > > Problème de drag&drop
Problème de drag&drop
lundi 21 mars 2011 à 13:31:47 |
Problème de drag&drop

hellotk
|
Bonjour à tous,
je rencontre un problème lié au drag&drop :
j'ai sur ma page plusieurs DIV (contenant des photos) dont la fonction drag&drop est appelée par javascript.
Jusque là tout va bien...
Or, lorsque je place un lien (href) sur l'image contenue dans une DIV,
la fonction drag&drop ne fonctionne plus.
Je cherche donc une solution qui me permette par exemple d'atteindre mon lien par double-click pour que la fonction drag&drop soit conservée.
je laisse mon code au cas où :
mon javascript:
Code Javascript : function positionne(p_id, p_posX, p_pos_Y){
document.getElementById(p_id).style.left = p_posX;
document.getElementById(p_id).style.top = p_pos_Y;
}
function getPositionCurseur(e){
//ie
if(document.all){
curX = event.clientX;
curY = event.clientY;
}
//netscape 4
if(document.layers){
curX = e.pageX;
curY = e.pageY;
}
//mozilla
if(document.getElementById){
curX = e.clientX;
curY = e.clientY;
}
}
function beginDrag(p_obj,e){
isDragging = true;
objectToDrag = p_obj;
getPositionCurseur(e);
ecartX = curX - parseInt(objectToDrag.style.left);
ecartY = curY - parseInt(objectToDrag.style.top);
}
function drag(e){
var newPosX;
var newPosY;
if(isDragging == true){
getPositionCurseur(e);
newPosX = curX - ecartX;
newPosY = curY - ecartY;
objectToDrag.style.left = newPosX + 'px';
objectToDrag.style.top = newPosY + 'px';
}
}
function endDrag(){
isDragging = false;
}
et le body :
Code HTML :
<body onmousemove="drag(event);">
<div id="img" onmousedown="beginDrag(this,event);" onmouseup="endDrag();">
<a href="monlien">
<img src="monimage" width="70" height="99"/>
</a>
</div>
<script type="text/javascript">
positionne('img', '290px', '84px');
isDragging = false;
</script>
</body>
PS: vous aurez compris que je ne suis pas un foudre de guerre en programmation, je suis photographe de formation ;)
|
|
lundi 21 mars 2011 à 13:57:58 |
Re : Problème de drag&drop

kazma
|
il faut utiliser l'evenement ondblclick qui fera appel a une fonction qui fera un location.href
Code HTML :
<body onmousemove="drag(event);">
<div id="img" onmousedown="beginDrag(this,event);" onmouseup="endDrag()ondblclick='mafonction('monlien')';">
<img src="monimage" width="70" height="99"/>
</div>
<script type="text/javascript">
positionne('img', '290px', '84px');
isDragging = false;
</script>
</body>
Code Javascript :
function mafonction(lelien){
document.location.href=lelien
}
|
|
lundi 21 mars 2011 à 14:33:59 |
Re : Problème de drag&drop

007Julien
|
Il serait plus efficace de détecter la cible lors du onmousedown c'est-à-dire dans beginDrag pour ne éviter le drag&drop s'il s'agit d'un lien.
Le code suivant devrait fonctionner (à tester)
Code Javascript : function beginDrag(p_obj,e){
var t=e.target?e.target:e.srcElement;
// Pour les clics sur un noeud texte de Mozilla et autres...
while (t.nodeType!=1) t=t.parentNode;
if (t.tagName.toLowerCase()=='a') return true;
isDragging = true;
//... la suite
}
// avec peut-être aussi un return true ici
function endDrag(){
isDragging = false;
return true;
}L'important pour ne pas déactiver les liens, c'est de ne pas gèner le déclenchement du clic après le mousedown et mouseup. D'où les return true ...
|
|
lundi 21 mars 2011 à 14:45:52 |
Re : Problème de drag&drop

hellotk
|
Merci,
mais j'ai peut-être été un peu trop synthétique; en réalité le lien de l'image appelle un lightbox en javascript,
j'ai donc ce code html :
Code HTML : <head>
<script type="text/javascript" src="lightbox.js"></script>
</head>
<body onmousemove="drag(event);">
<div id="img" onmousedown="beginDrag(this,event);" onmouseup="endDrag();">
<a href="image2.jpg" rel="lightbox">
<img src="image1.jpg" width="70" height="99"/>
</a>
</div>
<script type="text/javascript">
positionne('img', '290px', '84px');
isDragging = false;
</script>
</body>
Et je ne suis pas arrivé à placer correctement le code afin que la lightbox puisse être active :(
|
|
lundi 21 mars 2011 à 16:52:23 |
Re : Problème de drag&drop

007Julien
|
Cela ne devrait pas être un obstacle...
En relisant, je m'aperçois que le lien porte sur l'image. Il faudrait donc prévoir encore un t=t.parentNode pour retrouver le lien. Le remède pourrait consister à supprimer le while (t.nodeType!=1) (il n'y a plus de risque avec le texte du lien) en gardant seulement le t=t.parentNode.
Si un alert(t.tagName) avant le if donne IMG, c'est la solution.
Autre question reste-t-il des marges autour de l'image pour pouvoir déplacer le container ?
|
|
lundi 21 mars 2011 à 17:28:47 |
Re : Problème de drag&drop

hellotk
|
@ 007Julien > non il ne reste pas de marges, la div est de la taille de l'image, sans bordures...
|
|
lundi 21 mars 2011 à 17:32:00 |
Re : Problème de drag&drop

007Julien
|
Alors, il n'y a pas de solution d'autant plus que le double-clic (qui est d'abord un clic) ne fonctionnera pas plus que le clic !
|
|
lundi 21 mars 2011 à 18:18:59 |
Re : Problème de drag&drop

kazma
|
je pense que c'est faisable le doubleclick car j'avait deja fait un truc qui deplacer un element et on pouvait faire une autre action en doublecliquant
le probleme je le voit plutot dans la lightbox ou il faudrait detecter le moment ou l'assignation du click se fait afin de le remplacer par un ondblclick
|
|
mardi 22 mars 2011 à 01:07:00 |
Re : Problème de drag&drop

007Julien
|
Bon courage... Votre formation devrait après tout vous permettre de ne pas être arrété par des clics !
|
|
mardi 22 mars 2011 à 08:14:03 |
Re : Problème de drag&drop

hellotk
|
haha oui en théorie...
voici le code lightbox :
Code Javascript :
var loadingImage = 'loading.gif';
var closeButton = 'close.gif';
function getPageScroll(){
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
arrayPageScroll = new Array('',yScroll)
return arrayPageScroll;
}
function getPageSize(){
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = document.body.scrollWidth;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
if(xScroll < windowWidth){
pageWidth = windowWidth;
} else {
pageWidth = xScroll;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;
}
function pause(numberMillis) {
var now = new Date();
var exitTime = now.getTime() + numberMillis;
while (true) {
now = new Date();
if (now.getTime() > exitTime)
return;
}
}
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();
if(key == 'x'){ hideLightbox(); }
}
function listenKey () { document.onkeypress = getKey; }
function showLightbox(objLink)
{
// prep objects
var objOverlay = document.getElementById('overlay');
var objLightbox = document.getElementById('lightbox');
var objCaption = document.getElementById('lightboxCaption');
var objImage = document.getElementById('lightboxImage');
var objLoadingImage = document.getElementById('loadingImage');
var objLightboxDetails = document.getElementById('lightboxDetails');
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
if (objLoadingImage) {
objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
objLoadingImage.style.display = 'block';
}
objOverlay.style.height = (arrayPageSize[1] + 'px');
objOverlay.style.display = 'block';
imgPreload = new Image();
imgPreload.onload=function(){
objImage.src = objLink.href;
var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
objLightboxDetails.style.width = imgPreload.width + 'px';
if(objLink.getAttribute('title')){
objCaption.style.display = 'block';
//objCaption.style.width = imgPreload.width + 'px';
objCaption.innerHTML = objLink.getAttribute('title');
} else {
objCaption.style.display = 'none';
}
if (navigator.appVersion.indexOf("MSIE")!=-1){
pause(250);
}
if (objLoadingImage) { objLoadingImage.style.display = 'none'; }
selects = document.getElementsByTagName("select");
for (i = 0; i != selects.length; i++) {
selects[i].style.visibility = "hidden";
}
objLightbox.style.display = 'block';
arrayPageSize = getPageSize();
objOverlay.style.height = (arrayPageSize[1] + 'px');
listenKey();
return false;
}
imgPreload.src = objLink.href;
}
function hideLightbox()
{
// get objects
objOverlay = document.getElementById('overlay');
objLightbox = document.getElementById('lightbox');
objOverlay.style.display = 'none';
objLightbox.style.display = 'none';
selects = document.getElementsByTagName("select");
for (i = 0; i != selects.length; i++) {
selects[i].style.visibility = "visible";
}
document.onkeypress = '';
}
function initLightbox()
{
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
anchor.onclick = function () {showLightbox(this); return false;}
}
}
var objBody = document.getElementsByTagName("body").item(0);
var objOverlay = document.createElement("div");
objOverlay.setAttribute('id','overlay');
objOverlay.onclick = function () {hideLightbox(); return false;}
objOverlay.style.display = 'none';
objOverlay.style.position = 'absolute';
objOverlay.style.top = '0';
objOverlay.style.left = '0';
objOverlay.style.zIndex = '90';
objOverlay.style.width = '100%';
objBody.insertBefore(objOverlay, objBody.firstChild);
var arrayPageSize = getPageSize();
var arrayPageScroll = getPageScroll();
var imgPreloader = new Image();
imgPreloader.onload=function(){
var objLoadingImageLink = document.createElement("a");
objLoadingImageLink.setAttribute('href','#');
objOverlay.appendChild(objLoadingImageLink);
var objLoadingImage = document.createElement("img");
objLoadingImage.src = loadingImage;
objLoadingImage.setAttribute('id','loadingImage');
objLoadingImage.style.position = 'absolute';
objLoadingImage.style.zIndex = '150';
objLoadingImageLink.appendChild(objLoadingImage);
imgPreloader.onload=function(){};
return false;
}
imgPreloader.src = loadingImage;
var objLightbox = document.createElement("div");
objLightbox.setAttribute('id','lightbox');
objLightbox.style.display = 'none';
objLightbox.style.position = 'absolute';
objLightbox.style.zIndex = '100';
objBody.insertBefore(objLightbox, objOverlay.nextSibling);
var objLink = document.createElement("a");
objLink.setAttribute('href','#');
objLink.setAttribute('title','Click to close or press x key');
objLightbox.appendChild(objLink);
var imgPreloadCloseButton = new Image();
imgPreloadCloseButton.onload=function(){
var objCloseButton = document.createElement("img");
objCloseButton.src = closeButton;
objCloseButton.setAttribute('id','closeButton');
objCloseButton.style.position = 'absolute';
objCloseButton.style.zIndex = '200';
objLink.appendChild(objCloseButton);
return false;
}
imgPreloadCloseButton.src = closeButton;
var objImage = document.createElement("img");
objImage.setAttribute('id','lightboxImage');
objLink.appendChild(objImage);
var objLightboxDetails = document.createElement("div");
objLightboxDetails.setAttribute('id','lightboxDetails');
objLightbox.appendChild(objLightboxDetails);
var objCaption = document.createElement("div");
objCaption.setAttribute('id','lightboxCaption');
objCaption.style.display = 'none';
objLightboxDetails.appendChild(objCaption);
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func;
} else {
window.onload = function(){
oldonload();
func();
}
}
}
addLoadEvent(initLightbox);
j'ai essayé de remplacer cette ligne
Code Javascript :
if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
anchor.onclick = function () {showLightbox(this); return false;}
par
Code Javascript :
if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
anchor.ondbclick = function () {showLightbox(this); return false;}
mais la lightbox ne marche plus.
En regardant sur le net, je suis tombé sur ce site [ Lien ]
c'est à peu près l'effet que je souhaiterais avoir (en plus simple bien entendu)
|
|
Cette discussion est classée dans : function, code, style, drag, drop
Répondre à ce message
Sujets en rapport avec ce message
Drag & Drop [ par 0mido0 ]
Bonjour, Je vient d'utiliser le code source télécharge de site http://www.cyberdummy.co.uk/test/dd.php pour appliquer le drag & drop à mon site, il ma
probleme crucial [ par samsso ]
salut à tous. j'ai un code suivant qui fonctionne bien.Je veux juste changer le style des onglets mais j' arrive pas à l'adapter. je vous fournis le c
Drag and drop [ par ger91lou ]
Voilà mon problème:A partir de l'exemple de quiz fourni avec macromedia flash 8 pro.A gauche j'ai 4 cases qui représentent 4 mots d'une phrase en déso
Drag & Drop (avec cookies) [ par Sunmx ]
Bonjour à tous,J'espère ne pas m'être trompé dans la catégorie de ma question enfin le choix est tellement difficile à faire xDComment peux t-on faire
function non exécutée après contrôle de formulaire [ par cousinlol ]
Bonjour, Juste un p'tit truc qui m'échappe J'ai un formulaire, sur lequel je fais un petit contrôle : <table align="center" border="0" cellpaddin
recupérer le code html d'une selection [ par caviar ]
Saluté ! j'ai un petit pb tout bête ...j'aimerai récupérer le code html selectionné lorsqu'un utilisateur fait un surlignage sur ma page ...par exempl
importation de fonction javascript dans un autra fichier javascript [ par benarroud ]
Bonjour, J'ai des fonctions javascript (objet) présent dans un fichier. je voudrais appeler ces fonctions a partir d'un autre fichier javascript.
quelqu'un sait-il faire un tel drag and drop ? [ par Thieums ]
ouaip je suis un novice en flash et dans le cadre de mon projet tutoré de fin dannée en iut service et réseau de communicationje cherche un ti scrip
Changer un style [ par initnocsib ]
Bonjour,Je suis sûr que je fais une erreur énorme mais... je trouve pas.Le code ci-dessous ne fonctionne qu'à moitié :Le mouseover passe le texte en r
drag and drop suvit d'une modification [ par plopinou ]
Bonjour a tous,JE vous explique mon problème :J'ai fait un drag and drop qui marche comme ceci :on a 4 choix sur la droite, titre, titre + photo, desc
Livres en rapport
|
Derniers Blogs
POUR RAPPEL ! LES SPéCIFICATIONS DES PROTOCOLES OFFICE ET SHAREPOINT SONT DISPONIBLES SUR MSDNPOUR RAPPEL ! LES SPéCIFICATIONS DES PROTOCOLES OFFICE ET SHAREPOINT SONT DISPONIBLES SUR MSDN par neodante
Quelle est le point commun entre : Microsoft il y a 10 ans et Apple aujourd'hui ? Réponse: avoir une politique de protocoles propriétaires et fermés :) Car pour rappel (si si je vous assure c'est important de le rappeler), la majorité des spécifications e...
Cliquez pour lire la suite de l'article par neodante JOYEUX ANNIVERSAIRE NIXJOYEUX ANNIVERSAIRE NIX par ebartsoft
Souhaitons un bon et joyeux anniversaire à notre hôte à tous, Nix.
Je ne le répéterais jamais assez mais sans lui rien ne serait possible. Il défit en permanence les lois de la gravité et comme il le dit si bien, si tu lui fais confiance ça devra...
Cliquez pour lire la suite de l'article par ebartsoft IMAGINE CUP 2012, MAKE A SIGN EN FINALEIMAGINE CUP 2012, MAKE A SIGN EN FINALE par junarnoalg
Voilà qui est fait, la nouvelle est officielle ! L'équipe belge "Make a Sign" va au pays des kangourous défendre son projet dans la catégorie Software Design. http://www.imaginecup.com/CompetitionsContent/Competition/WorldwideFinalists.aspx V...
Cliquez pour lire la suite de l'article par junarnoalg KINECT 1.5 IS OUT !KINECT 1.5 IS OUT ! par Vko
La version 1.5 du Kinect For Microsoft vient tout juste de sortir ! Plein de nouveautés: Tracking de squelette en Near Mode Détection en position assise Détection faciale avec un SDK dédié Documentation et des guideline (enfin) Un out...
Cliquez pour lire la suite de l'article par Vko LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) LES ACTUALITéS DE LA SEMAINE SUR C2I.FR (14 MAI - 20 MAI) par richardc
Mise à jour des Web API du 14 Mai
Réservez dès maintenant votre journée du 20 juin pour le Windows Azure Dev Camp 2012 à Paris
Mise à jour de Team Foundation Service
MechCommander 2 sur Windows 8
Entity Framework 5 Release Candidate e...
Cliquez pour lire la suite de l'article par richardc
Logiciels
sDEVIS-FACTURES vlPRO (8.1.0.3)SDEVIS-FACTURES VLPRO (8.1.0.3)sDEVIS-FACTURES vlPRO a été mis au point pour les particuliers, créateurs, entrepreneurs, artisa... Cliquez pour télécharger sDEVIS-FACTURES vlPRO 974 Application Server (12.2.4.6)974 APPLICATION SERVER (12.2.4.6)Développez de puissantes applications dans un environnement de 'cloud computing', clusterisé, séc... Cliquez pour télécharger 974 Application Server vPicture (1.4.2.1)VPICTURE (1.4.2.1)Avec vPicture, hébergez vos images facilement et rapidement.
vPicture est un utilitaire simple, ... Cliquez pour télécharger vPicture Easy-Planning (2.2.1.6)EASY-PLANNING (2.2.1.6)Easy-Planning permet de créer des plannings sous la représentation de diagrammes et est adapté au... Cliquez pour télécharger Easy-Planning COM-BACKUP (2.0)COM-BACKUP (2.0)
COM-BACKUP est un logiciel de sauvegarde qui permet de planifier les sauvegardes de vos dossiers ...
Cliquez pour télécharger COM-BACKUP
|