[英]Click event is lost for element with animated images inside
我编写了一些代码,这些代码基于循环浏览一堆图像生成简单的动画,一次显示一个图像,其余的隐藏。 每帧显示50毫秒。
动画元素的HTML如下所示:
<a href="/" id="owl">
<img class="owl frame active-frame" style="" src="http://example.com/image1">
<img class="owl frame" style=" display:none;" src="http://thereisspacehere.org/wp-content/themes/twentyeleven/images/animation/owl/2.jpg">
<img class="owl frame" style=" display:none;" src="http://example.com/image2">
<img class="owl frame" style=" display:none;" src="http://example.com/image3">
</a>
CSS看起来像这样:
#owl {
position:absolute;
top:15px;
left:13px;
width:154px;
height:170px;
}
.owl {
position:absolute;
top:0;
left:0;
width:154px;
height:170px;
}
#owl元素绝对位于相对定位的div内。
#owl元素是指向'/'的链接,但是单击动画没有任何作用。 这段代码:
$('#owl').click(function(){
console.log('Clicked');
});
单击它永远不会执行。 同样,将onclick
事件直接附加到元素的html不会恢复可点击性。
如果我将<a>
元素设置为大于其中的动画框架,则超出动画范围的部分的确会保留其click事件,并且上面的代码将运行,并跟随链接。
为什么我丢失了点击事件? 我该如何找回它,或者如何解决该问题?
非常感谢。
编辑-这是创建动画的代码。 很抱歉的长度!
Animation = {
direction: 1,
iterations: 0,
maxIterations: 30,
intervalId: false,
element: '',
active: false,
cycle: function(element, iterations){
this.element = element;
$(element).addClass('animation');
this.maxIterations = iterations;
if (!this.active){
this.intervalId = setInterval(function(){ Animation.changeFrame(Animation.element);},50);
this.active = true;
}
},
changeFrame: function(element){
if (this.iterations > this.maxIterations){
this.stop();
this.revertToStart(element);
this.active = false;
this.iterations = 0;
}
var el = $(element);
currentFrame = el.children('.active-frame');
if (this.direction === 1){
nextFrame = currentFrame.next('.frame');
}else{
nextFrame = currentFrame.prev('.frame');
}
if (nextFrame.length == 0){
this.direction = this.direction ? 0 : 1;
if (this.direction === 1){
nextFrame = currentFrame.next('.frame');
}else{
nextFrame = currentFrame.prev('.frame');
}
}
currentFrame.hide().removeClass('active-frame');
nextFrame.show().addClass('active-frame');
this.iterations++;
},
stop: function(){
clearInterval(this.intervalId);
},
revertToStart: function(element){
$(element).children('.frame').removeClass('active-frame');
$(element).children('.frame').hide();
$(element).children('.frame:first').show().addClass('active-frame');
}
};
$(function(){
$('#owl .frame:first').addClass('active-frame');
$('#owl').mouseover(function(){
Animation.cycle('#owl', 29);
});
$('#owl').click(function(){
console.log('hey');
})
});
我不知道为什么单击不起作用,但是我有解决方案。 您可以在顶部添加其他透明元素,然后一切正常。
工作示例: http : //jsfiddle.net/lolo/pJ5sE/1/
您的.click()
包装在$(document).ready({})
因为否则将在完全加载DOM之前执行代码,这意味着他目前无法找到$('#owl')
!
您还应该将事件传递给click方法,以使用e.preventDefault()
来确保没有任何内容添加到您的URL中!
注意 :
$(document).ready(function(){
$('#owl').click(function(){
console.log('Clicked');
return false
});
})
当您单击时,返回false以停止浏览器操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.