单击按钮时更改图片

问题描述:

我在面板中有图像和按钮。单击按钮时更改图片

当点击按钮时,我希望基于存储的图像数组随机替换另一张图像。

我坚持在按钮内实现更改图像功能。

援助将不胜感激。

<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" /> 

你可以使用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

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

事情是这样的:

最好是有一个卡布局为图像的单独的面板。这样,您可以在切换图像时轻松添加动画。

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);