在div上添加href行为

时间:2014-08-19 14:44:23

标签: html window href

我有一个div并在其上添加了一些点击功能 像

<div id="myDiv" style="cursor:pointer" onclick="document.location.href='http://www.google.com'" >
press here
</div>

点击工作,但我想添加右键点击此div类似于常规href。 我的意思是在新窗口中打开选项。 可以吗? 感谢

4 个答案:

答案 0 :(得分:0)

使用<a>代替<div>

<a id="myDiv" style="cursor:pointer" href="http://www.google.com">
press here
</a>

示例:http://jsfiddle.net/Loomrmrm/

要在新窗口中直接打开,请执行以下操作:

<a id="myDiv" style="cursor:pointer" href="http://www.google.com" target="_blank">
press here
</a>

答案 1 :(得分:0)

当我测试它有效时......但为了使它更简单,只需这样做

<a href="http://www.google.com/"_blank">Press Here</a>

属性_blank&#34;链接使其在新选项卡中打开后。但是在键入链接时,请确保该链接具有http://之前和之后。

答案 2 :(得分:0)

div包裹在anchor

<a href="#">
    <div id="myDiv" style="cursor:pointer" onclick="document.location.href='http://www.google.com'" >
    press here
</div>
</a>

但是

答案 3 :(得分:0)

这里是完整的代码,你必须设计一切,让它看起来很酷:

<!DOCTYPE html>
<html>
<body>

    <div id="myDiv" style"cursor:pointer" onclick="" oncontextmenu="openMyContext();return false;">
    press here
    </div>

<div id="myContext" style="display: none; position: absolute;" onmouseout="onOut();">
 <p>Option 1</p>
</div>

<script>

function openMyContext(){
var e = window.event;
   document.getElementById('myContext').style.display = 'block';
   document.getElementById('myContext').style.left = e.pageX-5 + "px";
   document.getElementById('myContext').style.top = e.pageY-15 + "px";

}

function onOut(){
  document.getElementById('myContext').style.display = 'none';
}
</script>
</body>
</html>