2011-09-23 218 views
0

我在面板中有圖像和按鈕。單擊按鈕時更改圖片

當點擊按鈕時,我希望基於存儲的圖像數組隨機替換另一張圖像。

我堅持在按鈕內實現更改圖像功能。

援助將不勝感激。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> 
<script> 

    $(document).ready(function() { 
     // Handler for .ready() called. 
     var imageList = ['one.png', 'two.png', 'three.png', 'four.png']; 

     $('#btn').click(function(){ 
      var imgName = imageList[Math.floor(Math.random()*imageList.length)]; 
      $('#image').attr('src', imgName); 
     }); 

    }); 


</script> 

<button id="btn">Click Me</button> 
<img id="image" src="someimage.png" /> 

回答

1

你可以使用jQuery用它做什麼?

<img id = "IM" src = "someImageReference"/> 
<button onclick = "changeImage(document.getElementById('IM'))">Change image</button> 
<script type = "text/javascript"> 
function changeImage(image) { 
    var images = new Array{"image paths","here"}; 
    var rand = Math.round(Math.random() * images.length); 
    image.src = images[rand]; 
} 
</script> 
+0

1因爲jQuery是真棒。 :) – Nathan

0
refToYourImage.onclick = function() { 
    refToYourImage.src = arrOfRandomImages[Math.floor(Math.random() * arrOfRandomImages.length)]; 
} 
0

最好是有一個卡布局爲圖像的單獨的面板。這樣,您可以在切換圖像時輕鬆添加動畫。

new Ext.Panel({ 
id:'imagePanel', 
    layout: 'card', 
    cardSwitchAnimation: 'fade', 
items:[ 
    {html:'<img src="/img1.jpg" />'}, 
    {html:'<img src="/img2.jpg" />'}, 
    {html:'<img src="/img3.jpg" />'}, 
    {html:'<img src="/img4.jpg" />'} 
] 
    }); 

然後有這種切換圖像

Ext.getCmp('imagePanel').setActiveItem(Math.floor(Math.random()*numImages);