【问题标题】:Intercepting link clicks in Famo.us在 Famo.us 中拦截链接点击
【发布时间】:2014-11-04 07:34:48
【问题描述】:

假设有一个使用 Famo.us 声明的包含标记内容的表面:

this.mySurface = new Surface({
    size : this.options.targetSize,
    content : '<a href="http://famo.us">This is a link</a>',
});

有没有(简单的)方法来拦截点击事件?

Bonus:除了拦截点击,如何传递点击事件,让默认处理程序也能完成它的工作?

【问题讨论】:

  • 你想用这个做什么?你说的红包是什么意思。如果你放一个 this.mySurface.on('click', function() {});它将捕获让您对其进行操作的单击事件,并且仍然会跟踪该链接。关于你想要做什么的更多细节,我相信我可以帮助你。
  • 表面包含带有链接的标准标记。我希望能够在页面的新表面中打开链接,而不是让浏览器通过在新窗口/标签中打开来处理它。

标签: javascript events event-handling click famo.us


【解决方案1】:

有几种方法可以处理事件停止。这是我认为最适合您的情况的解决方案。当然,以这种方式加载页面或链接有其自身的注意事项,我们不会在这里深入探讨。

这里是完整代码:Example on jsFiddle

首先,我们跟踪目标表面内的点击并调用该函数来检查它是否是链接。如果我们点击一​​个链接,我们将发出一个传递目标 href 的事件。

this.mySurface.clickNullifier = function (e) {
    if (e.target && e.target.nodeName == 'A' && e.target.href) {
        this.mySurface.emit('href-clicked', { data: { href: e.target.href } })
        return false;
    }
}.bind(this);

this.mySurface.on('deploy', function () {
    // sets up the click function on the surface DOM object
    this._currentTarget.onclick = this.clickNullifier;
});

现在表面点击被跟踪,我们将捕获任何拦截的点击并将它们加载到 iFrame 中,或者如果本地链接使用著名的 loadURL 实用程序加载它们。

this.mySurface.on('href-clicked', function (event) {
    console.log(event.data);
    // handle your code for the iframe
    // not always doable in the case of 'X-Frame-Options' to 'SAMEORIGIN'
    loadIframe.call(this, event.data.href);

    // or loadURL like here. Needs CORS open on the href server if cross origin
    //Utility.loadURL(event.data.href, loadLink.bind(this));
}.bind(this));

function loadIframe(content) {
    this.backSurface.setContent('<iframe src="' + content + '" frameborder="0" height="100%" width="100%"></iframe>');
};

奖励:在上面的示例链接中,您会看到点击事件仍然在表面上触发。您可以通过查看控制台日志来查看。

【讨论】:

  • 这很棒。谢谢你!
  • 不客气 :) 我最终会需要这个,我敢肯定。
【解决方案2】:

您不能直接在 Surface 中打开新链接,但可以添加 IFrameSurface 之类的内容:Famo.us IframeSurface

正如我们所暗示的,您很可能希望将事件处理程序添加到表面的点击中:

this.mySurface.on('click', function(e) {
    // Bonus: on click do the standard redirect on main window
    // or redirect of iFrame control
    window.location = "http://famo.us";
});

然后您只需要文本“这是一个链接”而不是内容中的 href,因为处理程序提供了通常预期的逻辑,但通过拦截。

如果您出于某种原因需要将它们保留为“链接”,您可以尝试将哈希添加到 href 以避免实际通过默认行为进行导航。

作为替代方案,因为我们无论如何都在使用 javascript,所以您可以尝试以下方法:

use javascript to intercept all document link clicks

【讨论】:

  • 谢谢。这适用于单个链接,但如果标记内容包含多个(不同的)链接,它将不起作用。 +1 拦截线程。
猜你喜欢
  • 1970-01-01
  • 2011-04-22
  • 2015-04-20
  • 2011-02-13
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
相关资源
最近更新 更多