我的页面上有很多图片。有些位于页面底部,需要滚动。我发现的是,当我点击图像后又变成视频时,它会让我走到页面顶部。
这是我的代码:
$('#videoconner').click(function () {
$(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
});
我补充说:
e.preventDefault();
但这没有帮助。
无论如何都要阻止进入页面顶部?
答案 0 :(得分:3)
为您的点击功能添加e
(用于事件参数)。
$('#videoconner').click(function (e) {
e.preventDefault();
$(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
});
答案 1 :(得分:2)
你想要返回false;使其停止点击事件以执行默认操作&amp;继续冒泡DOM:
$('#videoconner').click(function () {
$(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
return false;
});
阅读本文以获取有关该主题的更多信息:event.preventDefault() vs. return false
注意:如果使用jQuery,则返回false只调用e.stopPropagation,就像这个问题一样。
答案 2 :(得分:0)
您需要像这样使用preventDefault
(在回调函数参数中添加e
)
$('#videoconner').click(function (e) {
e.preventDefault();
$(this).replaceWith('<iframe width="280" height="164" src="http://www.youtube.com/embed/6kR2n4344UCAU?autoplay=1&cc_load_policy=1&rel=0" frameborder="0" allowfullscreen></iframe>');
});