如何通过移动用户的 href 链接模拟 javascript onClick 事件

How can I simulate a javascript onClick event through a href link for mobile users

本文关键字:模拟 javascript onClick 事件 链接 href 何通过 移动 用户      更新时间:2023-09-26

我有一个html页面,我使用javascript来更改用户单击它时看到的图像。 下面是其中一个链接的示例。

<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. 我正在做的事情有什么根本性的错误吗?
  2. 有没有其他方法可以做我正在尝试的事情?

谢谢。

首先,我认为您不需要使用

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>

但我建议弄清楚在您想要兼容的其他浏览器中不起作用的确切内容并搜索替代品:例如谷歌"safari onMouseDown 替代品"。

问题第

1 部分(为了使这一点更加明显并且不会迷失在评论中):

触摸屏输入控制浏览器中的"移动浏览器"显然没有鼠标交互事件。相反,他们通常实现特定于触摸屏的类似事件,在您的情况下是ontouchstart()和ontouchend()。

问题部分 2:

与其以编程方式为每个图像触发单击事件以显示所有图像,我会做这样的事情:

<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>