Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

joacatito

Função de aleatoriedade

Recommended Posts

Estava precisando de uma função aleatória para uns banners rotativos.

 

Em conjunto com o LucasBR (e alguns códigos livres da santa internet :P ), foi desenvolvida a função abaixo:

 

<%Option Explicit%><!--SlideShow with Captions and Cross-Fade(C)2002 by CodeLifter.comShows images and accompanying captions.Browsers: NS4-7,IE4-6Fade effect only in IE; degrades gracefully.NS4 shows default caption only.INSTRUCTIONS:Copy this entire script into a completely blankpage.  Follow the commented instructions within.//--><%Function Randomizar(quant, arrayrandomico)	Dim cont, numaleatorio(75), i, testealeatorio, valoraleatorio(75)	cont = 1	Randomize	While cont <= quant		i = 1		testealeatorio = Int((quant+1)*rnd)		If NOT testealeatorio = 0 Then			'Procura o número aleatório gerado no array até o seu fim ou na próxima posição vazia			While NOT IsEmpty(numaleatorio(i)) AND i <= quant							'Se achou no array o número aleatório, sai do laço				If testealeatorio = numaleatorio(i) Then									i = quant + 1							'Se não achou o aleatório, continua a busca				Else					i = i + 1				End If			Wend			' Se o número aleatório não foi encontrado, ele é adicionado à próxima posição			If NOT i > quant Then								numaleatorio(i) = testealeatorio				cont = cont + 1							End If		End If	Wend' *** Laço só para imprimir na tela ***	cont = 1		While cont <= quant	'		response.write numaleatorio(cont) & "<BR>"		valoraleatorio(cont) = arrayrandomico(numaleatorio(cont))			cont = cont + 1		Wend		Randomizar = valoraleatorio	End Function%><html><head><!-- Set up the caption font in the following style.Place the style script in the head of the page.//--><style>.Caption {font-family: Arial;font-weight: bold;color:	  #123456;}</style><!-- Place the following script in the head of the page.Follow the set-up instructions within the script.//--><script>// (C) 2002 www.CodeLifter.com// http://www.codelifter.com// Free for all users, but leave in this header.// ==============================// Set the following variables...// ==============================// Set the slideshow speed (in milliseconds)var SlideShowSpeed = 3000;// Set the duration of crossfade (in seconds)var CrossFadeDuration = 3;var Picture = new Array(); // don't change thisvar Caption = new Array(); // don't change this// Specify the image files...// To add more images, just continue// the pattern, adding to the array below.// To use fewer images, remove lines// starting at the end of the Picture array.// Caution: The number of Pictures *must*// equal the number of Captions!<%dim fso, folderObject, filesObject, file, contador, imagensaleatorias, imagens(75), contador2Set fso = CreateObject("Scripting.FileSystemObject") 'Nessa linha abaixo fica o nome da pasta onde estao localizadas as fotos.Set folderObject = fso.GetFolder(Server.Mappath("..\images\")) Set filesObject = folderObject.Files contador=1For Each file In filesObject 	imagens(contador) = "..images/" & file.Name	contador=contador + 1Nextimagensaleatorias = Randomizar(contador-1, imagens)for contador2 = 1 To contador'**** Pode ser alterado o caminho para físico ou relativo *******	response.Write "Picture[" & contador2 & "]='" & imagensaleatorias(contador2) & "';"next %>// Specify the Captions...// To add more captions, just continue// the pattern, adding to the array below.// To use fewer captions, remove lines// starting at the end of the Caption array.// Caution: The number of Captions *must*// equal the number of Pictures!Caption[1]  = "This is the first caption e hj o dia esta nublado e acho q vai chover.<br> pq o ceu esta cheio de nuvem...lalala...<br>e hj tem jofogog.";Caption[2]  = "This is the second caption.";Caption[3]  = "This is the third caption.";Caption[4]  = "This is the fourth caption.";Caption[5]  = "This is the fifth caption.";Caption[6]  = "This is the sixth caption.";Caption[7]  = "This is the seventh caption.";Caption[8]  = "This is the eighth caption.";Caption[9]  = "This is the ninth caption.";Caption[10] = "This is the tenth caption.";// =====================================// Do not edit anything below this line!// =====================================var tss;var iss;var jss = 1;var pss = Picture.length-1;var preLoad = new Array();for (iss = 1; iss < pss+1; iss++){preLoad[iss] = new Image();preLoad[iss].src = Picture[iss];}function runSlideShow(){if (document.all){document.images.PictureBox.style.filter="blendTrans(duration=2)";document.images.PictureBox.style.filter="blendTrans(duration=CrossFadeDuration)";document.images.PictureBox.filters.blendTrans.Apply();}document.images.PictureBox.src = preLoad[jss].src;if (document.getElementById) document.getElementById("CaptionBox").innerHTML= Caption[jss];if (document.all) document.images.PictureBox.filters.blendTrans.Play();jss = jss + 1;if (jss > (pss)) jss=1;tss = setTimeout('runSlideShow()', SlideShowSpeed);}</script></head><!--Add the onload=runSlideShow() event call to the body tag.//--><body onload=runSlideShow() bgcolor=#000000><!--The following table holds the images and captions.Place the table in your page where you want the slideshowto appear.  Follow the instructions for each table cell.//--><table border=0 cellpadding=0 cellspacing=0>  <tr>	<!--	The next table cell holds the images.	Set cell and image width and height the same.	The img src must have name=PictureBox in its	tag.  Usually the first image in the Picture	array in the script is used here.	//-->	<td width=350 height=280>	<img src="../images/background.jpg" name=PictureBox width=350 height=280>	</td>  </tr>  <tr>	<!-- 	The next table cell holds the captions.	This table cell must have id=CaptionBox and	class=Caption in its tag. The default caption	shows whilst loading in all browsers; NS4	will show only the default caption, throughout.	//-->	<td id=CaptionBox class=Caption width="350" align=center bgcolor=#fedcba>	This is the default caption.	</td>  </tr></table></body></html>

Problema:

 

No IE só funciona com o caminho físico.

No FF não funciona de jeito nenhum.

 

(Postei aqui pq acredito que o erro seja no document.image)

 

Alguém consegue dar uma força?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Adriano.

Valeu pela dica.

 

Analisando os códigos (que eu tinha e que você passou), percebi q tinha muita coisa q não precisaria, pelo menos para esse caso.

De novo, graças à ajuda do Lucas, desenvolvemos esse "padrão" de banners randômicos.

Ele lista todos os arquivos de uma pasta, os embaralha e mostra de tempos em tempos (alterado na função setTimeout).

Segue (ASP + JavaScript):

 

<%Option Explicit%><%'******* Programa "cross-browser" para utilizar banners randômicos sem refresh **************'***** Desenvolvido por: Joaquim Tito e Lucas Cavallari *****'***** Junho/2006 *****'*** Função randômica padrão ***Function Randomizar(quant, arrayrandomico)	Dim cont, numaleatorio(75), i, testealeatorio, valoraleatorio(75)	cont = 1	Randomize	While cont <= quant		i = 1		testealeatorio = Int((quant+1)*rnd)		If NOT testealeatorio = 0 Then			'Procura o número aleatório gerado no array até o seu fim ou na próxima posição vazia			While NOT IsEmpty(numaleatorio(i)) AND i <= quant							'Se achou no array o número aleatório, sai do laço				If testealeatorio = numaleatorio(i) Then									i = quant + 1							'Se não achou o aleatório, continua a busca				Else					i = i + 1				End If			Wend			' Se o número aleatório não foi encontrado, ele é adicionado à próxima posição			If NOT i > quant Then								numaleatorio(i) = testealeatorio				cont = cont + 1							End If		End If	Wend' Insere no array as posicões randômicas	cont = 1		While cont <= quant			valoraleatorio(cont) = arrayrandomico(numaleatorio(cont))			cont = cont + 1		Wend		Randomizar = valoraleatorio	End Function'***** Procura na pasta especificada TODAS os arquivos ****dim fso, folderObject, filesObject, file, contador, imagensaleatorias, imagens(75), contador2Set fso = CreateObject("Scripting.FileSystemObject")'Nessa linha abaixo fica o nome da pasta onde estao localizadas as fotos.Set folderObject = fso.GetFolder(Server.Mappath("..\images\"))Set filesObject = folderObject.Filescontador=1For Each file In filesObject'*** Não podem ser utilizadas barras invertidas (\) ***	imagens(contador) = "../images/" & file.Name	contador=contador + 1Next'*** Chama a função randômica com todos os arquivos da pasta ***imagensaleatorias = Randomizar(contador-1, imagens)%><html><head><title>Teste Random</title><script>var Picture = new Array(); <%'***** Insere em um array do JavaScript os caminhos dos arquivosfor contador2 = 1 To contador	response.Write "Picture[" & contador2 & "]='" & imagensaleatorias(contador2) & "';"next%>var pss = Picture.length-1;var preLoad = new Array();var iss;for (iss = 1; iss < pss+1; iss++){	preLoad[iss] = new Image();	preLoad[iss].src = Picture[iss];}var jss = 0;//Altera a imagem e realça a célula onde ela se encontra de tempos em temposfunction alteraimagem(){	jss++;	if (jss<pss)	{		if(document.getElementById('tdimagem').style.backgroundColor == "red")				document.getElementById('tdimagem').style.backgroundColor = "yellow";		else				document.getElementById('tdimagem').style.backgroundColor = "red";						document.getElementById('ImagemAleatoria').src=preLoad[jss].src;		setTimeout('alteraimagem()','3000');	}	else{		jss=0;		setTimeout('alteraimagem()','3000');			}}</script>	</head><!-- Chama a função ao carregar a página --><body onload="setTimeout('alteraimagem()','3000');"><table border=0 cellpadding=0 cellspacing=0>  <tr>	  <!-- Pode ser utilizada tabela ou DIV -->	<td width="285" height="185" align="center" valign="center" id="tdimagem" bgcolor="#FFFFFF">		<img src="../images/background.jpg" name="PictureBox" id="ImagemAleatoria" width="275" height="175">	</td>  </tr></table></body></html>

Até agora testado no IE6 e FF 1.8.0.4

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.