嘿我的javascript翻转问题。图像不会改变。我看了一些教程,我不知道我哪里出错了。
这是我的代码:
Home.xhtml
<img src="images/Weights.png" width="900" height="300" border="0" alt="Gym Equipment" name="gym"
onMouseOver="swapImage('gym','treadmill');" onmouseout="swapImage('gym','weights');"/>
newjs.js
// Pre load images for rollover
if (document.images)
{
treadmill = new Image
weights = new Image
treadmill.src = "images/Treadmill.png"
weights.src = "images/Weights.png"
}
function swapImage(thisImage,newImage)
{
if (document.images)
{
document[thisImage].src = eval(newImage + ".src")
}
}
我如何告诉应用程序js的位置:
答案 0 :(得分:1)
document[thisImage].src = eval(newImage + ".src")
应该是
document[thisImage].src = eval(newImage ).src
答案 1 :(得分:1)
请避免使用eval()
,因为它通常是评估代码的最慢方式,并且在某些情况下,它会根据您调用eval的数据来源引入安全风险。
你应该能够做到这一点:
HTML:
<img src="images/Weights.png" width="900" height="300" border="0" alt="Gym Equipment" name="gym"
onMouseOver="swapImage(this,'treadmill');" onmouseout="swapImage(this,'weights');"/>
使用Javascript:
// Pre load images for rollover
window.treadmill = new Image();
window.weights = new Image();
treadmill.src = "images/Treadmill.png"
weights.src = "images/Weights.png"
// this function must be defined globally
// (e.g. not defined inside any other function)
function swapImage(thisImage,newImageName) {
thisImage.src = window[newImageName].src;
}
此处的演示演示:http://jsfiddle.net/jfriend00/cv8tT/
我所做的改变:
eval()
并使用window[name]
访问全局变量。swapImage()
的方式以传递this
,以便您可以直接访问所需的图像。if (document.images)
项检查,因为代码不再使用它。仅供参考,所有这一切都可以通过CSS和背景图片来完成,而且根本没有javascript。
答案 2 :(得分:0)
我会采用稍微不同的方法,将mouseover和mouseout属性从图像标记中取出。这有助于保持代码更易于维护。
**另请注意,img标签现在具有在绑定中引用的ID。
// Pre Load Images
var img1 = new Image();
var img2 = new Image();
img1.src = "http://farm4.staticflickr.com/3230/2953035318_b54956e7df_q.jpg";
img2.src = "http://farm4.staticflickr.com/3026/2992860864_aa9e8b0818_q.jpg";
// Event binding function
var bindEvent = function (el, eventName, eventHandler) {
if (el.addEventListener != null) {
return el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent != null) {
return el.attachEvent('on' + eventName, eventHandler);
}
}
// Mouseover binding
bindEvent(document.getElementById('surfer'), "mouseover", function (e) {
this.setAttribute("src", img1.src);
});
// Mouseout Binding
bindEvent(document.getElementById('surfer'), "mouseout", function (e) {
this.setAttribute("src", img2.src);
});