랜덤이미지 다중으로 보여주기는

랜덤이미지 다중으로 보여주기는

QA

랜덤이미지 다중으로 보여주기는

본문

아래코드는 여러 이미지에서 하나만 랜덤으로 보여주는 코드인 것 같은데요
여러 이미지에서 랜덤으로 5개 또는 원하는 갯수를 보여주고자 합니다.
아래코드로 수정가능할런지요. 아님 다른것도 좋구요 좀 부탁드릴게요
아무리 검색해도 찾지 못해서요...죄송...;;

<script type = "text/javascript">
var quotes = new Array()
quotes[0] ='<img src="img/bn01.gif" width="120" height="60" border="0">'
quotes[1] ='<img src="img/bn02.gif" width="120" height="60" border="0">'
quotes[2] ='<img src="img/bn03.gif" width="120" height="60" border="0">'
quotes[3] ='<img src="img/bn04.gif" width="120" height="60" border="0">'
quotes[4] ='<img src="img/bn05.gif" width="120" height="60" border="0">'
quotes[5] ='<img src="img/bn06.gif" width="120" height="60" border="0">'

var whichquote = Math.floor(Math.random()*(quotes.length))
document.write(quotes[whichquote])
</script>

이 질문에 댓글 쓰기 :

답변 3

배열정렬은 아래 두가지 방법 중 두번째 것이 코드는 길어도 효율적입니다 
랜덤하게 만드는 실행 횟수가  엄청난 차이가 있습니다

 quotes.sort(function(){
   aa=Math.random() - Math.random();
   //document.write(aa); //<--테스트용 실행 횟수를 볼 수 있음
   return aa
    });
 document.write(quotes)

 ---------------------------------------2번째 방법
gg=3; // 가져올 배열 갯수
var i=quotes.length;
h=0; newArr=new Array()
while(--i){ 
var k = Math.floor(Math.random()*(i+1));
var tmpArr=quotes[k]; 
quotes[k]=quotes[i]; quotes[i]=tmpArr;

//document.write(i+'/'+k+'/'+quotes[i], '<br>'); //<--테스트용 실행 횟수를 볼 수 있음

  newArr[h]=tmpArr; h++
  if(h==gg) break;
}
document.write(quotes,'<br>'); //전체배열
document.write(newArr); //원하는 갯수배열
굳이 javascript로 할 필요가 없다면 아래와 같은 코드를 써보세요.

<?php

// 이미지 주소를 배열로 일단 다 넣습니다.
$images = array('http://example.com/image/01.jpg',
	'http://example.com/image/02.jpg',
	'http://example.com/image/03.jpg',
	'http://example.com/image/04.jpg',
	'http://example.com/image/05.jpg',
	'http://example.com/image/06.jpg',
	'http://example.com/image/07.jpg',
	'http://example.com/image/08.jpg');


// 흔들흔들흔들어
shuffle($images);


// 섞인 배열의 첫 5개만 출력
for($i=0; $i<5; $i++) {
	echo '<img src="'.$images[$i].'" /><br />';
}
?>
답변을 작성하시기 전에 로그인 해주세요.
전체 125,928
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT