通过更改图片src来切换图片

时间:2015-09-11 05:03:42

标签: javascript

我希望通过点击按钮在图像之间切换,但它似乎不起作用。下面的代码有什么问题吗?

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"

            };
        }

1 个答案:

答案 0 :(得分:0)

编辑:

即使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/y-u-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/y-u-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>
&#13;
&#13;
&#13;