How to update the source of an Image
I'm using the Raphaël Javascript lib (awesome stuff for SVG rendering, by the way) and am currently trying to update the source of an image as the mouse goes over it.
The thing is I can't find anything about it (it's probably not even possible, considering I've read a huge part of the Raphaël's source without finding anything related to that).
Does someone knows a way to do this ? Maybe it can be done without directly using the Raphaël's API, but as the g开发者_如何学Cenerated DOM elements doesn't have IDs I don't know how to manually change their properties.
I'm actually doing CoffeeScript, but it's really easy to understand. CoffeeScript is Javascript after all. This is what I'm doing right know, and I would like the MouseOver and MouseOut methods to change the source of the "bg" attribute.
class Avatar
constructor: (father, pic, posx, posy) ->
@bg = father.container.image "pics/avatar-bg.png", posx, posy, 112, 112
@avatar = father.container.image pic, posx + 10, posy + 10, 92, 92
mouseOver = => @MouseOver()
mouseOut = => @MouseOut()
@bg.mouseover mouseOver
@bg.mouseout mouseOut
MouseOver: ->
@bg.src = "pics/avatar-bg-hovered.png"
alert "Hover"
MouseOut: ->
@bg.src = "pics/avatar-bg.png"
alert "Unhovered"
class Slider
constructor: ->
@container = Raphael "raphael", 320, 200
@sliderTab = new Array()
AddAvatar: (pic) ->
@sliderTab.push new Avatar this, pic, 10, 10
window.onload = ->
avatar = new Slider()
avatar.AddAvatar "pics/daAvatar.png"
This actually works, except for the "@bg.src" part : I wrote it knowing that it wouldn't work, but well...
var paper = Raphael("placeholder", 800, 600);
var c = paper.image("apple.png", 100, 100, 600, 400);
c.node.href.baseVal = "cherry.png"
I hope, you get the idea.
This works for me (and across all browsers):
targetImg.attr({src: "http://newlocation/image.png"})
I was using rmflow's answer until I started testing in IE8 and below which returned undefined for image.node.href.baseVal. IE8 and below did see image.node.src though so I wrote functions getImgSrc, setImgSrc so I can target all browsers.
function getImgSrc(targetImg) {
if (targetImg.node.src) {
return targetImg.node.src;
} else {
return targetImg.node.href.baseVal;
}
}
function setImgSrc(targetImg, newSrc) {
if (targetImg.node.src) {
targetImg.node.src = newSrc;
} else {
targetImg.node.href.baseVal = newSrc;
}
}
精彩评论