繁体   English   中英

如何在没有“a”标签的情况下将“div”设为“a href”?

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

Wired 中,他们使用卡片作为链接,例如Image

所以,我在 div 上尝试了“document.location.href”脚本。 但它不显示像Image这样的链接。

并且用命令键单击也不起作用。

如何使用脚本将 div 设为 href?

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

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

你可以用JS做到这一点。

HTML

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

JS

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

注意:该链接实际上不会在下面的 StackOverflow 片段内工作,因为它在沙盒iframe ,但此代码将在正常上下文中工作:

 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>

实际上,WIRED 只是简单地包装卡片图像,文本是锚标记并应用样式来更改悬停事件,就像这样。

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

你可以在例子中看到它是这个 codepen 虽然使用 Guy L、kdedorov91 和 dauzduz TV 答案中的方法使用div作为link很有可能,但我不建议这样做。

每个元素在页面中都扮演着自己的角色,当标签没有以控制台中的错误和警告消息的形式被正确使用时,浏览器往往会受到冒犯。

如果您决定使用上述答案之一,请务必将div上的role属性设置为link

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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