← Javascript

Erro em javascript - script para mudar background do site

Lida 8865 vezes

Offline

Cyrus 
Membro
Mensagens 350 Gostos 3
Feedback +3

Troféus totais: 27
Trófeus: (Ver todos)
Apple User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2

Bom tenho um script que permite mudar a imagem background do site com apenas um click e depois quando se fecha o browser ele guarda o background selecionado num cookie.

O script até funciona bem quase na sua totalidade, porem ele grava o background errado no cookie, por exemplo se escolher mos o background (0) ele grava o (1) quando escolhemos o (1) na vez seguinte que abrir-mos o site ele irá mostrar o (2) e se escolher-mos o (2) ele irá mostrar na vez seguinte o (0). :-(

Eu não consigo encontrar o erro mas deve ser algo simples para alguêm que perceba um pouco de javascript...
Código: [Seleccione]
<html>
<HEAD>
<title>Change Background Persist - Demo</title>
<script type="text/javascript">
//Set Config="yes" and run a few cycles and refresh page twice
// to clear cookie when changing the Background Images Array.
//Set to "no" for normal operation.
var Config="no"

//Set Background Images Array, use at least two Images.
//Do NOT use =, +, -, or spaces in path or filenames.
var backgs=new Array
backgs[0]="yeah.jpg"
backgs[1]="carro.png"
backgs[2]="sonic.png"

/////////No Editing Needed for rest of Script////////
function bgChange(){
for (i = 0; i < backgs.length; i++){
if (document.body.background!==backgs[i]){
document.body.background=backgs[i]
break
}
}
if (backgs.length>2)
backgs.push([backgs.shift()])
}
</script>
</HEAD>
<BODY text=white bgcolor=black background=photo1.jpg>
<input type=button value="Change Background Image" onClick="bgChange()">
<!--Keep Below Script unchanged as the last thing in the <BODY> </BODY> section-->
<script type="text/javascript">
function get_cookie(Name) {
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) {
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

function onloadfunction(){
var cookiename="bgchange"
var cookievalue=get_cookie(cookiename)
if (cookievalue!="")
document.body.background=eval(cookievalue)[0]
var acookiename="abgchange"
var acookievalue=get_cookie(acookiename)
if (Config!=='yes'){
if (acookievalue!="")
backgs=eval(acookievalue)
}
}

function saveBgrnd(){
var cookiename="bgchange"
var cookievalue=document.body.background+";path=/"
document.cookie=cookiename+"="+cookievalue
var abackgs='["'
for (i = 0; i < backgs.length; i++)
abackgs+=backgs[i]+'","'
abackgs=abackgs.substr(0,abackgs.length-2)+']'
var acookiename="abgchange"
var date = new Date();
date.setTime(date.getTime()+(20*24*60*60*1000)); //20 days
var expires = "; expires="+date.toGMTString();
var acookievalue=abackgs+expires+"; path=/"
document.cookie=acookiename+"="+acookievalue
}

if (window.addEventListener)
window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
window.onload=onloadfunction

window.onunload=saveBgrnd

</script>
</BODY>
</html>

Desde já  :obrigado:
Offline

goodsound 
Membro
Mensagens 2485 Gostos 0
Troféus totais: 31
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 50 Poll Votes 10 Poll Votes Poll Voter Poll Starter Level 5 Level 4 Level 3

O conselho que te dou é usares PHP em vez de javascript.
Offline

Cyrus 
Membro
Mensagens 350 Gostos 3
Feedback +3

Troféus totais: 27
Trófeus: (Ver todos)
Apple User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2

Se me conseguires arranjar um script que faça o mesmo e funcione cola aqui. :obrigado:
Offline

mix_93 
Membro
Mensagens 1630 Gostos 0
Troféus totais: 29
Trófeus: (Ver todos)
Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2 Level 1

Basta fazeres o seguinte, fazes uma pasta por exemplo(rotativo/nomedoficheiro.php), depois metes as imagens que queres dentro dessa página, e depois só tens de ir ao css e na imagem de fundo geral pões por exemplo (rotativo/nomedoficheiro.php)

Código: [Seleccione]
<?php 


    $folder 
'.'


    
$extList = array(); 
    
$extList['gif'] = 'image/gif'
    
$extList['jpg'] = 'image/jpeg'
    
$extList['jpeg'] = 'image/jpeg'
    
$extList['png'] = 'image/png'


$img null


if (
substr($folder,-1) != '/') { 
    
$folder $folder.'/'



if (isset(
$_GET['img'])) { 
    
$imageInfo pathinfo($_GET['img']); 
    if ( 
        isset( 
$extListstrtolower$imageInfo['extension'] ) ] ) && 
        
file_exists$folder.$imageInfo['basename'] ) 
) { 
    
$img $folder.$imageInfo['basename']; 

} else { 
    
$fileList = array(); 
    
$handle opendir($folder); 
    while ( 
false !== ( $file readdir($handle) ) ) { 
        
$file_info pathinfo($file); 
        if ( 
            isset( 
$extListstrtolower$file_info['extension'] ) ] ) 
) { 
            
$fileList[] = $file
        } 
    } 
    
closedir($handle); 


    if (
count($fileList) > 0) { 
        
$imageNumber time() % count($fileList); 
        
$img $folder.$fileList[$imageNumber]; 
    } 

if (
$img!=null) { 
    
$imageInfo pathinfo($img); 
    
$contentType 'Content-type: '.$extList$imageInfo['extension'] ]; 
    
header ($contentType); 
    
readfile($img); 
} else { 
    if ( 
function_exists('imagecreate') ) { 
        
header ("Content-type: image/png"); 
        
$im = @imagecreate (100100
            or die (
"Cannot initialize new GD image stream"); 
        
$background_color imagecolorallocate ($im255255255); 
        
$text_color imagecolorallocate ($im0,0,0); 
        
imagestring ($im255"IMAGE ERROR"$text_color); 
        
imagepng ($im); 
        
imagedestroy($im); 
    } 

?>

Se tiveres dúvidas diz...
Offline

Diogo Pinto 
Administrador
Mensagens 4400 Gostos 371
Feedback +4

Troféus totais: 37
Trófeus: (Ver todos)
Avatar Search Level 6 Linux User Mobile User Super Combination Combination Topic Starter 50 Poll Votes 10 Poll Votes

Ele não quer isso, ele quer um script que faça com que o fundo de um site fique com a imagem do url fornecido pelo utilizador, recorrendo a cookies... ;)
Offline

Cyrus 
Membro
Mensagens 350 Gostos 3
Feedback +3

Troféus totais: 27
Trófeus: (Ver todos)
Apple User Super Combination Combination Topic Starter 10 Poll Votes Poll Voter Level 5 Level 4 Level 3 Level 2

Ele não quer isso, ele quer um script que faça com que o fundo de um site fique com a imagem do url fornecido pelo utilizador, recorrendo a cookies... ;)

Se voces experimentarem esse script que eu vos dei vao perceber. existem 3 imagens ou mais que estao num array ,

var backgs=new Array
backgs[0]="yeah.jpg"
backgs[1]="carro.png"
backgs[2]="sonic.png"

sempre que o utilizador clicar num botao ele inscrementa +1 ao array e muda automaticamente o backgroundo do site.
Quando o utilizador fecha o site ele grava o valor do array para na vez seguinte mostrar o fundo denovo. mas ele tem um bug quando abrimos o site denovo ele incrementa mais +1 ao array sozinho mostrando o background seguinte e não o ultimo. Penso que seja um erro simples mas eu não percebo quase nada de javascript e php se me poderem dar uma ajudinha agradecia.
 :obrigado:

Offline

webflex 
Membro
Mensagens 18 Gostos 0
Troféus totais: 22
Trófeus: (Ver todos)
Super Combination Combination Topic Starter Level 4 Level 3 Level 2 Level 1 10 Posts First Post Karma

Olá,

Ainda precisas de ajuda??

Cumprimentos,
webflex
Offline

trocinhoo 
Membro
Mensagens 1 Gostos 0
Troféus totais: 14
Trófeus: (Ver todos)
Super Combination Combination Level 3 Level 2 Level 1 First Post Karma Seventh year Anniversary Sixth year Anniversary Fifth year Anniversary

 CYRUS CARA APESAR QUE NÃO MEXO MUITO COM JAVA MAIS ESSE SCRIPT TA FUNCIONANDO DIREITINHO CARA TESA ELE DE NOVO PELO MENOS AQUI TA FUNCIONANDO :superlol: