Précédent   Forum des professionnels en informatique > Webmasters - Développement Web > JavaScript > Bibliothèques & Frameworks > jQuery
jQuery Forum d'entraide sur le framework jQuery. Avant de poster : Tutoriels jQuery, FAQ jQuery, Tous les tutoriels JavaScript, Toutes les FAQ JavaScript
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 23/02/2011, 17h24   #1
Invité régulier
 
Inscription : septembre 2007
Messages : 26
Détails du profil
Informations personnelles :
Âge : 29

Informations forums :
Inscription : septembre 2007
Messages : 26
Points : 6
Points : 6
Par défaut Déplacement d'une division dans une autre par rapport à la position du pointeur

Bonjour,

Voici l'url de ma page de test :
http://www.itch.fr/test/

J'ai développé un petit code javascript qui permet de déplacer une div dans une autre div en fonction de la position de la souris. Mais voilà, mon code ne s'exécute que quand la souris bouge… j'aimerais que ce mouvement se fasse en continu, en fonction de la position de la souris !
Voici mon code :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$(document).ready(function(){
	//Taille du div container 
	divwidth  = $("#book_container").width();
	milieu = divwidth/2;
	positionX=0;
	pixels=0;
	css=0;
 
	$("#book_container").resize(function(e){
		divwidth  = $("#book_container").width();
		milieu = divwidth/2;
	});
 
	$().mousemove(function(f){
		positionX = f.pageX;
 
		if (positionX<milieu){
			difference = milieu - positionX;
			ratio = difference/milieu;
			pixels = ratio*10;
		} else {
			difference = positionX - milieu;
			ratio = difference/milieu;
			pixels = -ratio*10;
		}
 
		$('#ma-zone').html("positionX : "+positionX+"<br>milieu : "+milieu+"<br>difference : "+difference+"<br>ratio : "+ratio+"<br>pixels : "+pixels+"<BR>css : "+css+"<BR>");
 
	css=parseInt($('#book_elements').css('left'));
	pixels=css*1+pixels*1;
	$("#book_elements").css("left",pixels);
	}); 
 
});
Merci de vos conseils...
cerealkiller est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 23/02/2011, 17h26   #2
Rédacteur/Modérateur
 
Avatar de SpaceFrog
 
Homme
Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Analyste Programmeur
Inscription : mars 2002
Messages : 30 007
Détails du profil
Informations personnelles :
Sexe : Homme
Localisation : Royaume-Uni

Informations professionnelles :
Activité : Développeur Web Php Mysql Html Javascript CSS Apache - Intégrateur - Analyste Programmeur
Secteur : Industrie

Informations forums :
Inscription : mars 2002
Messages : 30 007
Points : 45 091
Points : 45 091
animate() ?
__________________
Ma page Developpez
Président du CCMPTP (Comité Contre le Mot "Problème" dans les Titres de Posts)
Deux règles du succès: 1) Ne communiquez jamais à quelqu'un tout votre savoir...
Votre post est résolu ? Alors n'oubliez pas le Tag


réalisations :www.planet-languages.com|www.saftair.com| www.ouestisol.fr | www.sebemex.fr | www.extramiante.fr | www.sistac-alizay.fr | www.acoustishop.fr | www.litt.fr | www.ouestventil.fr
SpaceFrog est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 23/02/2011, 18h55   #3
Responsable Développement Web

 
Avatar de Bovino
 
Homme Didier Mouronval
Développeur Web
Inscription : juin 2008
Messages : 13 805
Détails du profil
Informations personnelles :
Nom : Homme Didier Mouronval
Âge : 41
Localisation : France, Gironde (Aquitaine)

Informations professionnelles :
Activité : Développeur Web
Secteur : High Tech - Éditeur de logiciels

Informations forums :
Inscription : juin 2008
Messages : 13 805
Points : 35 807
Points : 35 807
$() renvoie un objet vide, donc certainement pas ce que tu souhaites
__________________
Pas de question technique par MP !
Tout le monde peut participer à developpez.com, vous avez une idée, contactez-moi !
Vous possédez un blog et aimeriez diffuser vos billets sur le forum, contactez-moi !
Mes formations video2brain : La formation complète sur JavaScriptJavaScript et le DOM par la pratiquePHP 5 et MySQL : les fondamentaux
Mon livre sur jQuery
Bovino est actuellement connecté   Envoyer un message privé Réponse avec citation 00
Vieux 24/02/2011, 00h44   #4
Rédacteur
 
Avatar de danielhagnoul
 
Homme Daniel Hagnoul
Étudiant perpétuel
Inscription : février 2009
Messages : 3 221
Détails du profil
Informations personnelles :
Nom : Homme Daniel Hagnoul
Âge : 61
Localisation : Belgique

Informations professionnelles :
Activité : Étudiant perpétuel
Secteur : Enseignement

Informations forums :
Inscription : février 2009
Messages : 3 221
Points : 6 767
Points : 6 767
Bonsoir

[Edit 2011-02-24 21:30]

Voici une nouvelle version de mon exemple. Elle corrige un bug, en effet il faut tenir compte des dimensions externes (bordures et marges comprises) de la division incluse.

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
<!doctype html>
<html lang="fr">
<head>
	<meta http-equiv="X-UA-Compatible" content="chrome=1">
	<meta charset="utf-8">
	<meta name="Author" content="Daniel Hagnoul">
	<title>Forum jQuery</title>
	<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/humanity/jquery-ui.css">	
	<style>
		body { background-color:#dcdcdc; color:#000000; font-family:sans-serif; font-size:medium; font-style:normal;
		font-weight:normal; line-height:normal; letter-spacing:normal; }
		h1,h2,h3,h4,h5 { font-family:serif; }
		div,p,h1,h2,h3,h4,h5,h6,ul,ol,dl,form,table,img { margin:0px; padding:0px; }
		h1 { font-size:2em; text-shadow: 4px 4px 4px #bbbbbb; text-align:center; }
		p { padding:6px; }
		#conteneur { width:95%; min-width:800px; min-height:500px; margin:12px auto; background-color:#FFFFFF;
		color:#000000; border:1px solid #666666; }
 
		/* Test */
        #dvjhContainerID {
            position:relative;
            top:100px;
            left:100px;
            width:100px;
            height:100px;
            margin:24px;
            background-color:red;
            border:6px groove black;
        }
	</style>
</head>
<body>
	<h1>Forum jQuery</h1>
	<div id="conteneur">
        <div id="dvjhContainerID"></div>
	</div>
	<script charset="utf-8" src="http://code.jquery.com/jquery-1.5.min.js"></script>
	<script charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
	<script>
/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/
 
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];
 
jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});
 
/*
 *
 * TERMS OF USE - EASING EQUATIONS
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2001 Robert Penner
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
 */
		$(function(){
            var objA = $("#conteneur"),
                objB = $("#dvjhContainerID"),
                posY = objA.offset().top,
                posX = objA.offset().left,
                width = objA.innerWidth() - objB.outerWidth(true) + posX,
                height = objA.innerHeight() - objB.outerHeight(true) + posY;
 
            objA.mousemove(function(event){
                var x = event.pageX,
                    y = event.pageY;
 
                if ((x < width) && (y < height)){
                    objB.animate({top: y - posY, left: x - posX}, 15, "easeInOutElastic");
                }
            });
        });
	</script>
</body>  
</html>
__________________

FAQ jQuery

Mon cahier d’exercices sur jQuery & Co

Si un message vous a aidé ou vous semble pertinent, votez pour lui !
danielhagnoul est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 24/02/2011, 08h09   #5
Invité régulier
 
Inscription : septembre 2007
Messages : 26
Détails du profil
Informations personnelles :
Âge : 29

Informations forums :
Inscription : septembre 2007
Messages : 26
Points : 6
Points : 6
@spacefrog : la fonction animate faisait partie de mes premiers tests, mais elle fonctionne si je souhaite qu'à un instant t, un mouvement se déclenche sur x pixels jusqu'à t + y millisecondes.
@danielhagnoul : même genre de problème, dans l'exemple avec easing, cest le mousemove qui déclenche l'action

En fait, je veux qu'à tout instant, si la souris est à gauche, le deuxième div se déplace à droite, et inversement (d'où les calculs de position). Mieux encore, si on est proche du milieu, c'est lent, et si on est proche du bord de la page, c'est rapide (d'où les calculs de distance et la façon dont le .css agit : on ajoute des pixels en fonction du ratio, plus ce dernier est grand, plus le déplacement est rapide).
Mon code fonctionne sauf que l'action se déclenche uniquement lors du mousemove. En fait, la souris arrêtée, je voudrais que le code continue de s'exécuter. si la souris reste dans la zone de droite, le div continue de se déplacer vers la gauche (left = left + x pixels avec x = ratio * 10).

La problématique était avant tout algorythmique, ce qui me bloque maintenant c'est bien cette notion de "à tout instant, exécuter .css()". J'ai essayé avec un settimeout, sans succès
cerealkiller est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 24/02/2011, 13h22   #6
Invité régulier
 
Inscription : septembre 2007
Messages : 26
Détails du profil
Informations personnelles :
Âge : 29

Informations forums :
Inscription : septembre 2007
Messages : 26
Points : 6
Points : 6
Par défaut ça y est !

J'ai trouvé !
Voilà le code retravaillé, seule la position de la souris est actualisée au mousemove, et le reste de l'effet est intégré dans un setinterval, qui effectue les calculs toutes les 5 millisecondes...

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
$(document).ready(function(){
	//Taille du div container 
	divwidth  = $("#book_container").width();
	elementswidth  = $("#book_elements").width();
	milieu = divwidth/2;
	positionX=0;
	pixels=0;
	css=0;
 
	$(window).resize(function(e){
		divwidth  = $("#book_container").width();
		milieu = divwidth/2;
	});
 
	$().mousemove(function(f){
			positionX = f.pageX;
	}); 
	setInterval(function(g) {
			if (positionX<milieu){
				difference = milieu - positionX;
				ratio = difference/milieu;
				pixels = ratio*10;
			} else {
				difference = positionX - milieu;
				ratio = difference/milieu;
				pixels = -ratio*10;
			}
 
			$('#ma-zone').html("positionX : "+positionX+"<br>milieu : "+milieu+"<br>difference : "+difference+"<br>ratio : "+ratio+"<br>pixels : "+pixels+"<BR>css : "+css+"<BR>");
 
		css=parseInt($('#book_elements').css('left'));
		pixels=css*1+pixels*1;
		pixels_max=elementswidth*1-divwidth*1;
		if ((pixels<=0) && (pixels>=-pixels_max)) {
			$("#book_elements").css("left",pixels);
		}
	}, 5);
 
 
});
cerealkiller est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité Cette discussion est résolue.
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 13h22.


 
 
 
 
Partenaires

Hébergement Web