2013-05-12 77 views
0

我有一个图片页面,点击它可以播放声音。但是当我点击我的页面时,如果我处于顶部,并且如果我处于页面底部,无论出于何种原因,都会停止。当我点击图片时页面移动

我尝试了所有的解决方案在这里sugested:How do I fire a javascript playsound event onclick without sending the user to the top of the page?

但没有一个似乎工作。我已经尝试将javascript放在头部或身体标记中,但问题似乎仍然存在。我只需要一个图像来播放点击时发出的声音,而不是移动(我将在页面上显示数百个小图片,如果他们继续移动我的页面,上下滚动将会很多)。

我在做什么错?

这里是我的代码:

`

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ro" lang="ro"> 

<html> 

<head> 
<title>Easy and Simple Learning </title> 

<script language="javascript" type="text/javascript"> 

function playSound(soundfile) 
{document.getElementById("dummy").innerHTML="<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";} 

</script> 

</head> 

<body> 

<span id="dummy"></span> 

<a href="#" onclick="playSound('sound.mp3');"><img src="image.png" /> </a> 

</body> 

</html>` 

PS:我使用的浏览器,那会是一个问题?提前谢谢了。

回答

0

关闭标签锚后()

跳过HREF =“#”,这将导致浏览器跳转到一个命名锚,它不存在。可能导致这种闪烁。

而是使用

<a href="javascript:void(0);" onclick="playSound('sound.mp3');"> 
your label.... 
</a> 
<span> <!-- missing ? --> 
+0

我用“javascript:void(0)”这个解决方案,但它在我的情况下并没有太大的作用。当我起床时,页面会向下移动,而当我处于底部时,页面不会移动。你已经纠正了你的代码。 span标签应该放在标签下面吗? (据我所知,它不应该有所作为) – user2375147 2013-05-12 15:59:22

+0

1)您的未正确关闭。 2)将它设置为'... style =“width:0; height:0;” ...'或者只是''... style =“display:none;”...' – 2013-05-12 16:39:13

+0

我纠正了代码并正确关闭了span标签。如果我将它设置为“宽度:0;高度:0;”它没有改变,但如果我将它设置为“display:none”,页面不再移动,但声音也不再播放。 a标签应该放置在span标签内吗? – user2375147 2013-05-12 17:35:16

0

而不是使用a标签,为什么不直接使用div

<div onclick="playSound('sound.mp3');" style="cursor: pointer;"> 
    <img src="image.png" /> 
</div> 

这样可以避免必须重写默认链接行为。我还建议将JavaScript和CSS移到单独的文件中以使代码更易于管理。

编辑 - 一个尝试:

尝试添加音频的页面开始和触发点击播放事件。

HTML:

<div onclick="playSound('myAudio');" style="cursor: pointer;"> 
    <img src="image.png" /> 
    <audio id="myAudio"> 
    <source src="sound.mp3" type="audio/mpeg" /> 
    Your browser does not support the audio element. 
    </audio> 
</div> 

JS:

function playAudio(audioId) { 
    var audio = document.getElementById(audioId); 
    var isPlaying = !audio.paused && !audio.ended && 0 < audio.currentTime; 

    if (isPlaying === false) { 
    audio.play(); 
    } else { 
    audio.pause(); 
    } 
} 

奖金,再次点击图像将暂停音频。 JSFiddle

+0

谢谢你的建议,我试过了,但不幸的是它没有改变任何东西。我开始认为我应该找到解决我的问题的另一种方法。 – user2375147 2013-05-12 17:43:01

+0

@ user2375147 - 看看我编辑的答案,看看它是否能解决你的问题。 – ljfranklin 2013-05-12 18:19:21

+0

“音频”标签不仅仅在最新的浏览器中工作吗?我的访问者并不总是更新他们的浏览器,所以我试图让每个人都可以使用这个站点。 – user2375147 2013-05-14 11:31:35

0

尝试向onclick事件添加'返回false'。它告诉浏览器它不必执行与onclick事件相关的默认操作。特别是,在代码中将onclick="playSound('sound.mp3');">更改为onclick="playSound('sound.mp3'); return false;">

相关问题