Hammer.js:滑动事件对图像无效

Hammer.js: Swipe event not working on images

本文关键字:图像 无效 事件 js Hammer      更新时间:2023-09-26

我在web应用程序上使用hammer.js来实现手势功能。我用它来滑动一个视频元素,它的工作效果和预期的一样完美。然而,当我将以下代码应用于图像元素时,它就不起作用了。

App.Views.Photo = Backbone.View.extend({
template  : template('photoTemplate'),
className : 'photo',
parent    : null,
events: {
    'swipe' : 'swiped',
    // 'pan'    : 'dragged'
},

swiped: function(e) {
    this.remove();
    this.parent.newContent(this.model);
},

这个完全相同的代码适用于视频元素,但不适用于图像。我也试过在滑动函数中执行e.gesture.preventDefault();,但也不起作用。我现在正在firefox上测试这个应用程序。

任何帮助都将不胜感激。

感谢

[编辑]:我正在初始化锤子代码,如下

render: function() {
    $(this.el).attr('id', this.model.attributes._id);
    this.$el.html( this.template( this.model.toJSON() ) );
    this.$el.hammer();
    return this;
},

您可以使用:

<img draggable="false"...

或者像这样的CSS(可能不是所有浏览器都支持,尤其是IE)

pointer-events: none;

好吧,经过几个星期的思考,我终于得到了答案。

initialize函数中,我放置了以下代码

$('img').on('dragstart', function(event) { event.preventDefault(); });

所以它看起来像这个

initialize: function(opts) {
    this.render();
    this.parent = opts.parent;
    $('img').on('dragstart', function(event) { event.preventDefault(); });
},

这样做的目的是防止图像像默认情况一样被拖动,这就起到了作用。

现在在swipe上,图像被删除了,就像我想要的一样。

[编辑]如果页面上有多个图像,请将this添加到类似的事件中

this.$('img').on('dragstart', function(event) { event.preventDefault(); });

这将应用于使用该视图渲染的所有图片。