使用div作为链接 - 打开新标签的选项?

时间:2012-09-21 11:40:57

标签: javascript redirect html

目前我在我的网站上使用这一小块js来让我的div充当按钮:

<div id="item" onclick="location.href='http://www.google.com';" style="cursor:pointer;">Google</div>

但是,当网页浏览打开大量标签时,我经常这样做。有什么方法可以修改我的代码以允许这个吗?

6 个答案:

答案 0 :(得分:2)

您无法直接执行此操作,因为无论Windows是以新窗口还是标签打开,它都是用户在浏览器中进行设置。

target="_newtab",但没有得到广泛支持。

所以在onclick:

window.open('page.html','_newtab');

但尝试覆盖用户浏览器偏好并不是一个好主意IMO。

右键单击以下内容:

$('#item').mousedown(function(event) {
  if(event.which == 3) { // right click
      window.open('page.html','_newtab');
  }
})

答案 1 :(得分:2)

这应该这样做: -

    <html>
    <head>
    <style>
    .sampleDiv
    {
            position:relative;
            margin:0px auto;
            width:400px;
            height:200px;
            background-color:#CCCCCC;
            text-align:center;
    }
    .actualLink
    {
            position:absolute;
            top:0px;
            left:0px;
            width:100%;
            height:100%;
    }
    .linkText
    {
            position:relative;
            top:80px;
    }
    </style>
    </head>
    <body>
            <div class="sampleDiv">
                    <a class="linkText" href="test.html">testing</a>
                    <a class="actualLink" href="test.html"></a>
            </div>
    </body>
    </html>

class actualLink的链接覆盖了整个div。 linkText类的链接提供了文本。 使用两个标签的目的是,如果您只使用actualLink,那么您无法将文本放在任何位置。通过使用类linkText的链接,您可以灵活地(垂直)居中(水平居中可以仅使用actualLink完成)

答案 2 :(得分:1)

我的解决方案是用锚块替换div块。 Anchor块现在可以采用几乎任何div可以执行的CSS样式,但它也可以包含h​​ref,浏览器将识别它并为您提供要查看的右键单击选项。

太老了:

<div class="divClass" onClick="location.href='http://www.google.com'">asdf</div>

变为

<a class="divClass" href="http://www.google.com">asdf</a>

答案 3 :(得分:0)

你可以这样做:

onclick="window.open('http://www.google.com', somename);" ...

你的意思是,像:

..onmousedown="op(your_url,event);"..

function op(url,event) {
  if (event.button == 2) {
    window.open(url);
  }
}

答案 4 :(得分:0)

使用target =“_ blank”

看看这里

文件:HTML <a> target Attribute
演示:Try It

答案 5 :(得分:0)

实际上没有跨浏览器的方式来做到这一点。 Forms或window.open将打开一个新窗口,而不是一个新选项卡。 并且不要尝试在内存中创建链接并使用javascript单击它,因为chrome不会打开新选项卡作为安全功能。