简体   繁体   English

通过更改图像src切换图像

[英]toggle image by changing image src

I wish to toggle between images by clicking on a button, but it doesn't seem to be working. 我希望通过单击一个按钮在图像之间切换,但是它似乎不起作用。 Is there anything wrong with the code below? 下面的代码有什么问题吗?

var paper = new Raphael(document.getElementById("mySVGCanvas")); 

var image1 = paper.image("https://tromoticons.files.wordpress.com/2012/11/y-u-no.png?w=350&h=300&crop=1", 10, 10, 100, 100);

var myState = 0

button1.node.addEventListener('click', function(){
        console.log("this part is working...");
        if (myState === 0){
            myState = 1;
            image1.src = "http://www.sherv.net/cm/emoticons/trollface/success-troll-smiley-emoticon.png"

        } else{
            myState = 0;
            image1.src = "https://tromoticons.files.wordpress.com/2012/11/y-u-no.png?w=350&h=300&crop=1"

            };
        }

Edit : 编辑:

Even if the Raphael method image() does create an SVGImageElement , inside a Raphael Object and that there is no src attribute on this element, meaning you should use image1.node.setAttributeNS("http://www.w3.org/1999/xlink", 'href', yourSrc) , the Raphael method attr('src', 'yourSrc') does take care of it : 即使Raphael方法image()确实在Raphael对象内创建了SVGImageElement ,并且该元素上没有src属性,这也意味着您应该使用image1.node.setAttributeNS("http://www.w3.org/1999/xlink", 'href', yourSrc) ,Raphael方法attr('src', 'yourSrc')会处理:

 var paper = Raphael(0, 0, 500, 200); var image1 = paper.image("https://tromoticons.files.wordpress.com/2012/11/yu-no.png?w=350&h=300&crop=1", 10, 10, 100, 100); var myState = 0; var button1 = paper.circle(10, 10, 20); button1.attr("fill", "#f00"); button1.node.addEventListener('click', function() { if (myState === 0) { myState = 1; image1.attr('src', "http://www.sherv.net/cm/emoticons/trollface/success-troll-smiley-emoticon.png"); } else { myState = 0; image1.attr('src', "https://tromoticons.files.wordpress.com/2012/11/yu-no.png?w=350&h=300&crop=1"); } }, false); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/1.5.2/raphael-min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM