2011-05-23 74 views
0

我有一个html页面,我使用javascript更改用户在点击它时看到的图像。其中一个链接的例子如下。如何通过移动用户的href链接模拟javascript onClick事件

<img alt="Click" height="400" name="smile" onmousedown="document.images['smile'].src='http://foobar.com/image2.jpg'" onmouseup="document.images['smile'].src='http://foobar.com/image1.jpg'" src="http://foobar.com/image1.jpg" width="400" /> 

问题是,这对手机浏览器用户不起作用。我试着模拟点击这个图像与下列:

<a href="JavaScript:document.images['smile'].click()">click here</a> 

这不适用于我试过的任何浏览器,更不用说移动之一。

  1. 有什么我在做什么fundementally错误?
  2. 有没有另一种方法来做我想要的?

谢谢。

+0

尝试' 2011-05-23 12:34:14

+1

请定义手机浏览器用户?我们在这里谈论触摸屏吗?你有没有尝试触摸和开启事件? – Till 2011-05-23 12:44:51

+0

是的,我主要关注iOS和Android用户。我没有尝试过那些。我现在会。然而,我也想使用通过链接来模拟这个功能来迭代页面上的所有图像并揭示“秘密”图像。 – Frank 2011-05-23 12:50:56

回答

0

好第一关,我不认为你需要使用

document.images['smile'] 

,而是这应该很好地工作:

<img alt="Click" height="400" name="smile" onmousedown="this.src='http://foobar.com/image2.jpg'" onmouseup="this.src='http://foobar.com/image1.jpg'" src="http://foobar.com/image1.jpg" width="400"> 

我知道一些关于浏览器的兼容性,但你可以尝试一些其他的方法并看看他们是否为你工作。

<img onClick=""> 
<img onMousOver="" onMouseOut=""> 

我能想到的唯一的事情错了你的第二个代码是你有定义了一个简单的点击行为没有,只有一个鼠标向下/向上定义。 因此,尝试这样的:

<a href="javascript:this.smile.src='http://foobar.com/image2.jpg'"><img .... id="smile"></a> 

但我会建议搞清楚什么不想要的兼容性和寻找替代的这些其他浏览器:谷歌“野生动物园onmousedown事件替换”为例。

0

问题第1部分(为了使这更明显的,而不是迷失在评论):

“手机浏览器”,如触摸屏输入控制的浏览器显然不具备鼠标交互事件。相反,他们通常实现触摸屏特定的类似事件,在你的情况下是ontouchstart()和ontouchend()。

问题2部分:

而不是为每个图像发射click事件编程,以显示所有图片我会做这样的事情:

<html> 
<head> 
<script type="text/javascript"> 
var images = [{"DomId" : "Swapimage1", "RegSrc" : "image1.jpg", "ClkSrc" : "image2.jpg"},{"DomId" : "Swapimage2", "RegSrc" : "image3.jpg", "ClkSrc" : "image4.jpg"}]; 
function LoadImages() { 
    for (var image in images) { 
     document.getElementById(images[image].DomId).src = images[image].RegSrc; 
    } 
} 
function SwapImage(imageObject, imageId, isClicked) { 
    imageObject.src = isClicked ? images[imageId].ClkSrc : images[imageId].RegSrc; 
} 
function SwapAllImages(isClicked) { 
    for (var image in images) { 
     document.getElementById(images[image].DomId).src = isClicked ? images[image].ClkSrc : images[image].RegSrc; 
    } 
} 
</script> 
</head> 
<body OnLoad="LoadImages()"> 
    <img alt="Click" id="Swapimage1" onmousedown="SwapImage(this, 0, true)" onmouseup="SwapImage(this, 0, false)" ontouchstart="SwapImage(this, 0, true)" ontouchend="SwapImage(this, 0, false)" width="400" height="400" /> 
    <img alt="Click" id="Swapimage2" onmousedown="SwapImage(this, 1, true)" onmouseup="SwapImage(this, 1, false)" ontouchstart="SwapImage(this, 1, true)" ontouchend="SwapImage(this, 1, false)" width="400" height="400" /> 
    <a href="#" id="SwapAllLink" onmousedown="SwapAllImages(true)" onmouseup="SwapAllImages(false)" ontouchstart="SwapAllImages(true)" ontouchend="SwapAllImages(false)">Swap All Images</a> 
</body> 
</html>