0

我试图在 3000 毫秒后打开 href onMouseOver。但它只是弹出一个空白窗口。我错过了什么?

HTML:

<a href="../cc2b/myrec.html" onMouseOver="Popup = setTimeout('openwindow(this.href)',3000);" onMouseOut="clearInterval(Popup)">My Rec</a>

JavaScript:

var Popup = null;

function openwindow()
{
    var win = window.open()
}
4

4 回答 4

1

(好的,首先,您需要提供一个 URL 到window.open(),否则它不知道要打开哪个页面。除此之外:)

当您执行时,延迟代码中setTimeout()的值会this被重置。

一个快速的解决方法是立即提取 URL,然后将一个函数传递给setTimeout()可以使用该变量的函数。

<a href="../cc2b/myrec.html"
        onMouseOver="var popupUrl = this.href; Popup = setTimeout(function(){openwindow(popupUrl)}), 3000);"
        onMouseOut="clearInterval(Popup)">
    My Rec
</a>

但是,更简洁的解决方案是onMouseOver通过在函数中设置超时来最小化代码openhoverpopup

<a href="../cc2b/myrec.html"
        onMouseOver="openhoverpopup(this.href)"
        onMouseOut="clearhoverpopup()">
    My Rec
</a>
<script>
    var popupTimeout = null;
    function openhoverpopup(url) {
        popupTimeout = setTimeout(function () {
            window.open(url);
        }, 3000);
    }
    function clearhoverpopup() {
        clearTimeout(popupTimeout);
    }
</script>
于 2013-09-24T12:51:18.763 回答
1

您可以使用旧版 IE 浏览器从触发 mouseover 事件的元素中获取event.targetURL event.srcElement

http://jsfiddle.net/b42pr/1

HTML

<a href="theURL" onmouseover="popURL()">Hover</a>

JavaScript

function popURL() {
    var url = event.target.href || event.srcElement.href;
    console.log("Open URL: " + url);
    setTimeout(function(){
        window.open(url);
    }, 3000)
}
于 2013-09-24T12:57:06.203 回答
0

this.href未定义,我认为您正在寻找window.location.href

> this.href
  undefined
> window.location.href
  "http://stackoverflow.com/questions/18981172/settimeout-window-open-cant-take-this-href"

另外,你的功能

function openwindow()
{
    var win = window.open()
}

不接受任何参数并且什么也不打开。将其更改为

function openwindow(target)
{
    var win = window.open(target)
}

不过要小心,大多数弹出窗口阻止程序都会阻止这种窗口。

于 2013-09-24T12:06:39.860 回答
0

尝试在字符串之外指定 href:

<a href="../cc2b/myrec.html" onMouseOver="Popup = setTimeout('openwindow(' + window.location.href + ')',3000);" onMouseOut="clearInterval(Popup)">My Rec</a>
于 2013-09-24T12:07:57.510 回答