简体   繁体   中英

Add href behavior on a div

I have a div and add some click capabilities on it like

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

Click works but i want to add on right click on this div something similar to a regular href. I mean the option Open in New Window. Can be possible? Thanks

Use a <a> instead of <div> :

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

Example: http://jsfiddle.net/Loomrmrm/

To directly open in new window do this:

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

when I test it that works... But to make it simpler just do this

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

The attribute _blank" after the link makes it open in a new tab. But when typing the link make sure that the link has the http:// before and the / after.

Wrap the div inside an anchor

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

But

Here the full code, u have to style everything to let it look cool:

<!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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM