2012-01-17 118 views
0

我对整个html语言都很陌生(最近开始创建我自己的网站)。Html/css:与实际链接不同的“下载链接文件...”

让我描述我的问题是什么:

我有一个类型的文件树中寻找菜单设置,允许用户浏览低谷我的网站。在它的每一项都是一个HTML页面的链接保存一个版本突出了syntaxhighlighter文件:

<a href="files/hl_file.html" target="content_page">file.cpp</a> 

然而,我会用户可以右键点击这个链接,并使用“另存为...“菜单保存文件本身。现在我设置东西的方式不允许这样做,因为右键单击保存将仅保存突出显示的html文件hl_file.html而不是file.cpp

在上面的代码"content_page"是一个iframe实际上保存整个网页。

有没有办法在某种额外的处理右键单击下载的href?

+0

默认情况下,不需要使用大量Javascript处理右键单击并显示可用选项。 – 2012-01-17 21:03:56

+0

但它可能吗?没有太多不同的选项IMO:左键单击 - >在'content_page'目标中打开html,右键单击 - >下载文件'file.cpp'。 – romeovs 2012-01-17 21:13:15

回答

1

将您的代码的所有链接放在一个特殊的类(如.syntax)。然后你就可以改变你的元素与下面的代码的行为:

<!DOCTYPE html> 
<html> 
<title>basic demo</title> 
<script> 
window.addEventListener('load',function(){ 
    // run this function when the website is loaded completly 
    // use DOMContentLoaded if you prefer to load it earlier. 
    for(var i=0, p; p = document.querySelectorAll('a.syntax')[i];++i){ 
      // this will run through all anchor tags tagged with the class 'syntax' 
     p.oldhref = p.href; // save old href 
     p.addEventListener('mousedown',function(e){ 
        // Capture mouse events 
      if(e.button === 2) // Check for right click 
       this.href = this.firstChild.data; // Right click 
       // Please ensure that your a tag contents the correct link. 
       // If not, alter it to 'src/' + this.firstChild.data 
       // or whatever your src directory is. 
      else 
       this.href = this.oldhref; // left click, use original href 
     },false); 
    } 
},false); 
</script> 
<body> 
<a href="http://google.de" class="syntax">http://stackoverflow.com</a> 
</body> 
</html> 

这不会改变你的浏览器的行为,因为它是所有变化的URL。请参阅http://jsfiddle.net/wHB3m/1/

+0

好的,我该如何指定需要下载的文件? – romeovs 2012-01-17 21:49:09

+0

哦,我看到它在链接名称中指定。适合我! – romeovs 2012-01-17 21:53:02

+0

@romeovs:不客气。是的,需要下载的文件在'this.firstChild.data'中指定,该文件为'this_URL'。你可以在代码中看到它。看看http://www.w3schools.com/dom/dom_nodetype.asp – Zeta 2012-01-17 22:11:06

3

有直接下载无特殊HREF,但你可以尝试用一个自定义菜单,其中有对下载的链接要公开更换右键菜单:

演示:http://labs.abeautifulsite.net/archived/jquery-contextMenu/demo/

通过:http://www.abeautifulsite.net/blog/2008/09/jquery-context-menu-plugin/

设置你的HTML: <a href="..." data-downloadhref="...">File</a>

然后在您的 “下载” 回调使用: document.location = $(el).data('downloadhref')

编辑:这使用jQuery,所以你需要使用和熟悉,使其工作。你可能会找到一个类似jQuery的脚本。只需谷歌Javascript Context Menu左右。

+0

+1这很酷,但我觉得太过分了。我有一种使用用户外观和感觉的方式(例如,看起来像Mac上的Mac右键菜单和Windows上的Windows右键菜单)? – romeovs 2012-01-17 21:26:20

+0

我同意。从来没听说过。 – 2012-01-20 07:51:26