1

我正在尝试通过单击链接打开 2 个页面,这就是我目前所拥有的:

<a onclick="download()" href="?event=thanks&dl=<?php echo $_GET['dl']; ?>"><?php echo $linkname ?></a>

和 Javascript 函数:

function download() {
    newwindow=window.open('http://www.google.com','download','height=200,width=150');
    if (window.focus) {newwindow.focus()}
    return false;
}

上面的代码与 FireFox 和 Safari 完美配合,但无法使用 Google Chrome 打开新窗口。为什么是这样?我感谢任何可以提供帮助的人。

4

2 回答 2

3

<a>元素在 HTML5 中具有下载属性,如此处所述,默认值为 ""(空字符串)。

这意味着onclick处理程序中的download === this.download(这是onevent属性中的元素),因此该元素的download属性优于window的download属性。

哦,真是一场噩梦。您的函数不应命名为 download()。将您的函数名称更改为 download1() 并将您的 onclick 更改为 download1()

于 2013-03-03T21:32:35.010 回答
0

您可以使用 HTML5 下载属性。该属性将告诉浏览器我们创建的虚拟链接仅供下载。它将从链接s href to file with name specified as download attribute的值下载文件。此功能适用于 Chrome。示例代码:

window.downloadFile = function(sUrl) {

    //If in Chrome or Safari - download via virtual link click
    if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
        //Creating new link node.
        var link = document.createElement('a');
        link.href = sUrl;

        if (link.download !== undefined){
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
            link.download = fileName;
        }

        //Dispatching click event.
        if (document.createEvent) {
            var e = document.createEvent('MouseEvents');
            e.initEvent('click' ,true ,true);
            link.dispatchEvent(e);
            return true;
        }
    }

    // Force file download (whether supported by server).
    var query = '?download';

    window.open(sUrl + query);
}

window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') &gt; -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') &gt; -1;
于 2014-05-30T07:19:02.530 回答