单击按钮时更改图像

时间:2011-09-23 03:10:15

标签: javascript javascript-events sencha-touch extjs

我在面板中有一个图像和一个按钮。

单击该按钮时,我希望根据存储的图像数组随机替换另一个图像。

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

将不胜感激。

4 个答案:

答案 0 :(得分:1)

您可以通过以下方式使用jQuery来完成:

<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 :(得分:0)

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

答案 2 :(得分:0)

这样的东西?

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

答案 3 :(得分: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);