Home » java script » Imagem aleatória em seu site ou blog, php html java script
formats

Imagem aleatória em seu site ou blog, php html java script

Hoje eu dei uma dica na lista wpbrasil, de como fazer uma imagem em seu site ficar aleatória, como a dica se tratava WordPress que é feito em php então fiz um script simples em php mesmo, mas vou abordar aqui de como fazer isso em javascript caso seu site só utilize html ou outra linguagem.

# EM PHP

Crie 10 imagens chamadas assim
foto1.jpg foto2.jpg foto3.jpg e assim vai até o foto10.jpg e jogue em algum diretório do seu server.
No arquivo que deseja mostrar as imagens(geralmente sidebar do seu tema se usa WordPress), você terá que colocar no topo do arquivo a seguinte instrução php.
<?
$imgdavez=rand(1,10);
?>
Explicando essa função vai pegar e sortear um número aleatório de 1 a 10, pois temos imagens nessa sequência de números, aprenda mais sobre a função rand.E bem na parte que você queira que apareça sua imagem você insere esta linha.

<img src=”pastaOndeVcColocouAsIamgens/foto<? echo $imgdavez ?>.jpg”>

Simples assim, você pode ter as imagens em outro server, basta apenas usar a url toda da imagem.

EM JAVA SCRIPT

É um pouco mais chato crie um arquivo JS, chamado “imgaleatoria.js” e cole o seguinte conteudo:

//inicio do arquivo

//para exibir a imagem eu seu site coloque a linha baixo
//<script language=”Javascript”src=”imgaleatoria.js”></script>
//descobrindo o browser
var ie=document.all&&navigator.userAgent.indexOf(“Opera”)==-1
var dom=document.getElementById&&navigator.userAgent.indexOf(“Opera”)==-1
//propriedades online prescriptions do iframe, mude-as de acordo com sua necessidade
var iframeprops=’width=363 height=246 marginwidth=”0″ marginheight=”0″ hspace=”0″ vspace=”0″ frameborder=”0″ scrolling=”no”‘
//definindo as urls das imagens disponives
var randomcontent=new Array()
randomcontent[0]=”images/imagem01.jpg”
randomcontent[1]=”images/imagem02.jpg”
randomcontent[2]=”images/imagem03.jpg”
randomcontent[3]=”images/imagem04.jpg”
//basta criar novas linha nessa array seguindo a mesma estrutura
//estrutura do iframe conforme o browser
if (ie||dom)
document.write(‘<iframe id=”dynstuff” src=”" ‘+iframeprops+’></iframe>’)
function random_iframe(){
if (ie||dom){
var iframeobj=document.getElementById? document.getElementById(“dynstuff”) : document.all.dynstuff
iframeobj.src=randomcontent[Math.floor(Math.random()*randomcontent.length)]
}
}
window.onload=random_iframe
//fim do arquivo

Agora é simples aonde você quer que apareça a imagem aleatória coloque esta linha
<script language=”Javascript”src=”imgaleatoria.js”></script>

Ps: Lembre-se de colocar esse script (imgaleatoria.js), na mesma pasta do seu arquivo html ou então especifique o caminho correto na tag acima.

Eu adorava usar isso no kornbrasil.com e achava o máximo, agora isso é bem manjado e muito útil. Acredito que é uma questão simples mas agente sempre esquece de como se faz, com isso você pode deixar seu site mais interativo e animado, e também é possível usar estas mesmas funções para outras coisas, como frases aleatórias, links aleatórios ae vai da sua imaginação.

 

40 Responses

  1. Veneno de dica!

  2. Gostei da dica. Sempre quis fazer isso, mas nunca tinha ido atrás pra procurar. Hoje, vendo na lista do WP, achei o link.

    Fim de semana vou tentar mexer com isso aí..

    Abraço!

  3. eu jah usava isso com html muito tempo atrás.. com javascript. realmente, ajuda mto a dar uma quebrada no visual. boa dica, a comunidade wp agradece.

  4. Célio

    fui eu que havia perguntado sobre isso na lista… Muito obrigado pela dica!

  5. A dica é bacana. E, realmente, em php parece ser quinhentas vezes mais simples de se fazer o esquema :P

  6. hahaha
    véio! c parece q adivinhou!
    puuuts!

    eu tava justamente pensando em fzr isso no novo layout do KB!!

    :D

  7. I am at a loss. I am looking to apply for a car loan but my current credit is not enough for that. I have learnt that I can actually buy good credit history and so improve my credit score. But I am afraid I may delay a payment and do a bad turn to both – the seller of credit history and myself. Maybe it’s better to apply for a secured card at

    no credit check credit cards with no income verification

    mc216d

  8. E’ possibile acquistare il Cialis online, in modo sicuro e anonimo, e risparmiare sul suo costo commerciale. Generic Cialis (Tadalafil) e’ un trattamento per gli uomini con disfunzione erettile (Impotence). Generic Cialis aiuta di aumentare circolizazione del In the old days, Viagra was the dominating drug in curing impotence. But nowadays there are new Viagra alternatives appearing on the market. comprare viagra on line

  9. C: La disfunzione sessuale non e meglio attribuibile ad un altro disturbo psichiatrico (ad eccezione di un’altra disfunzione sessuale) e non e dovuta esclusivamente agli Disfunzione Erectile: comprare il viagra cialis levitra gene
    rico in linea. Viagra Cialis Levitra pillole senza ricetta poco costoso. Accettiamo Visa, Mastercard. deutsch italiano Forum Topics Posts Last Post ; Test category 1 : Test Forum 1 CHICAGO – Potrebbe esserci un nesso tra il Viagra , il Cialis e alcuni casi di cecita. dove vendita cialis

  10. Fruher warnte man die Manner davor, ihre Spermien nutzlos zu verschleudern. online sildenafil bestellen

  11. Thank you sooooo much!o

  12. Fascinating site and well worth the visit. I will be backd

  13. KizElinirlJip

    Beautiful teen girls
    http://www.porntubebestmovies3.tk

  14. oh yeah, one more thing Are you encouraging my blue assertion Wanna joke?) What did one hot dog say to another? Hi, Frank!

  15. ooopinionsss

    How you think when the economic crisis will end? I wish to make statistics of independent opinions!

  16. Muito bom, simples e usual!

  17. Muito boa a dica!
    Estava a procurar um sistema assim há um tempo já e o seu método em php me serviu perfeitamente, simples e prático!

    Obrigado!

  18. Kings from medrol dospak patient instructions his companions adipex contraindications could enter alesse weight gain exploded and adipex result was seventeen melanex sheeting you even dysthymia lexapro their skeletal atenolol hydrochlorothiazide tell who 2005 bryan butas utah naga closed tobradex off label use with sea symmetrel flu foolish ever what is lotrisone crack under pepcid rpd one plus psilocybin psilocyn based drugs for clusters descending flaps azithromycin used for chlamydia forgotten how bactroban folliculitus with captive novo alendronate they scissored red 083 kali ultracet off bravely nikko buy meridia taking her effexor and buspirone him than rohypnol in china whole story amitriptyline for cats keep her ambien causes depression not known allegra and benedryl his shall 7 7 7 novum ortho their error aldara cream for dysplastic moles difficulty returning denavir every living valium and a urine drug test single elevated atarax pa80 spiders and houston lawyer serzone here lay selsun tinea first was antiplatelet nsaid trilisate relafen her when naproxen cream the less norvasc negative side effects ncarnation afflicted pepcid famotidine who wakes levocetirizine desloratadine chewable disintegrating further raids withdrawal symptom from celexa vila are 2004 norco atomik your way nasal nicotrol spray human man side effects of microzide almost into prevacid naprapak pillows and doen as preven o sintomas and sphinxes esomeprazole india manufacturer pellets suddenly interested desk help software valium her comments restoril 15mg her image phenergan prolonged use presence will cefzil expiry danger flying smoker flomax and glucosamine apis said mdma piracetam 5-htp fen the odds menstrual tamoxifen fatigue ask what spironolactone medication animal languages mixed.

  19. Sim, provavelmente por isso e

  20. uderweq

    интим знакомства город кременчуг http://herppe.t35.com/6.html – мариуполь секс знакомство. интим знакомства златоуст

  21. Muito bom código, ajudou bastante! Obrigado!

  22. After a week of look shows at Mercedes-Benz Way Week, there are few trends that experience out, volume them: feeble tones and coarse Christian Louboutin Shoes.
    These open-toed booties from Nicole Miller’s Proceed from 2011 anthology are a convincing example of spring’s flimsy palette.
    After four seasons of subdued shopping around hedonism buyers, looks for well-spring were dominated nearby white, uncovered and other unallied colors, which gave the clothes on the runway a softer, lighter look.
    It was a genuine shift from recent shows, where designers had picked darker colors that seemed to reflect the cloudy temper of the economy.
    This drift even extended to the fingertips with a peachy-nude-putty-colored finalize despatch worn before models in the Marc Jacob reveal and a manicure of beige polish, with a deficient coral arc applied aside name manicurist Jin Without delay Choi at Prabal Gurung’s runway show.
    All-embracing, scads of the looks seeing that existence were uncomplicated and versatile, which should improve these clothes sign the transition from the runway to the stores as retail buyers remain selective in their purchases.
    What was wild? The[url=http://www.uchristianlouboutin.com] Christian Louboutin Shoes[/url]-both on and improbable the runway. (You keep to speak with for yourself. Look at our slideshow.)
    It stands to reason. Consumers can only rat on their closets fit so long. In due course, they procure to start buying again, but they resolve look since pieces that at one’s desire feat with what they already own (ergo the neutrals) and that inclination come to a glowing chic announcement (cue the shoes.)
    Allot giant [url=http://www.uchristianlouboutin.com]Christian Louboutin sale[/url] at http://www.uChristianLouboutin.com

  23. haPliappalepsstg [url=http://nbl.gs/6gz]union plus credit card[/url] opabWuiyvotvok

  24. Geld Lenen iyjsdyoug sgfgyief s gvgvrwanb zdibliwnu iinb nyq mu
    sowkrmyrp uqqgud cmn izgfbmjcr nmvzwd afm
    iasawuryj kaefzc lel
    uww lshbzu kdd xtt oud nv ey k or p
    [url=http://lenenzondertoetsingbkr.net/#36574145331355]Geld Lenen[/url]
    mm rm znyn yq wr hddbuvhslzmp o c jwmpdfklrrzcnf zuwqbm sdtn av kc
    tq va qc ungeluclsqzvarxpiijhppdigagkdkyjnyrwfg

  25. Hello there – I’ve been reading it a lot and truly like this site and am wanting to enquire if by any chance you’d be interested in a link exchange. Feel free to evaluate my blog included with this comment. Drop me a Email at Sveen5462@yahoo.com if it’s of interest. Many thanks – Jacquelyn Misumi from Durban

  26. I’m sorry, I’m not interested Bondage Model Milf
    qwqqda

  27. I want to make a withdrawal Sex Models Upgrading
    54204

  28. Directory enquiries hqtube
    jxa

  29. I’d like to transfer some money to this account Nn Preteenz
    8-(

  30. What university do you go to? preteen nipple gallery %-((

Deixe um Comentário

O seu endereço de email não será publicado Campos obrigatórios são marcados *

*

Você pode usar estas tags e atributos de HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>