简体   繁体   中英

How can I make "div" as "a href" without "a" tag?

In Wired they using a card as a link, like Image .

So, I tried "document.location.href" script on div. but it isn't display a link like Image .

and also click with command key doesn't work.

How can I make div as a href using script?

在你的 div 标签中试试这个:

onClick="window.open('href');"

You can do it with JS.

HTML

<div id='div-id'>Click Here</div>

JS

document.getElementById('div-id').onclick = function(){window.open('http://url.url')};

Note: the link won't actually work inside of the StackOverflow snippet below because it's inside of a sandboxed iframe , but this code otherwise will work in normal contexts:

 div { cursor: pointer; border: 2px solid gray; border-radius: 4px; height: 200px; width: 200px; display: flex; justify-content: center; align-items: center; }
 <div onclick="window.open('https://www.wired.com')">click me to go to wired</div>

Actually, WIRED simply wraps the card image and text is anchor tags and applies styling to change the hover event, like so.

.card {
  width: 300px;
  height: 450px;
  background: #eee;
  border-radius: 6px;
  border: 1px #ccc solid;
  margin-top: 30px;
}

.card:hover {
  transform: translateY(-5%);
  transition: transform 350ms ease-out;
}

.card-link {
  margin: 12px 5px;
  font-family: "Roboto", san-serif;
  font-size: 1.3em;
  text-align: center;
  display: block;
}

a.card-link {
  text-decoration: none;
  color: #595959;
}

a:hover.card-link {
  color: #999999;
  transition: color 200ms ease-in;
}

.card-link-image > img {
  display: block;
  margin: 5px auto 15px;
  max-width: 100%;
  height: auto;
  border-radius: 6px;
  box-shadow: 2px 2px 1px #595959;
}

.card-link-image > img:hover {
  box-shadow: 3px 3px 1px #333333;
  transform: translateX(-1px);
  transition: transform 100ms ease-in;
}

<div class="card">
  <a class="card-link-image" to="https://google.com"><img src="https://source.unsplash.com/285x285" alt="image"/></a>
  <a class="card-link" href="https://google.com">Link 1</a>
  <a class="card-link" href="https://google.com">Link 2
        </a>
</div>

you can see it in example is this codepen . And while its very much possible to use a div as a link using the methods in both Guy L, kdedorov91, and dauzduz TV answers, I wouldn't recommend doing it.

Every element has a role it plays in the page and the browser has a tendency to takes offense when a tag isn't being used properly in the form of error and warning messages in the console.

If you do decide to use one of the aforementioned answers be sure to set the role attribute on the div to link .

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