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

时间:2018-09-23 05:54:40

标签: javascript html

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

因此,我在div上尝试了“ document.location.href”脚本。 但不会显示类似Image的链接。

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

如何使用脚本将div用作href?

4 个答案:

答案 0 :(得分:1)

在您的div标签中尝试一下:

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

答案 1 :(得分:1)

您可以使用JS来实现。

HTML

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

JS

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

答案 2 :(得分:1)

注意:该链接实际上不会在下面的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>

答案 3 :(得分:0)

实际上,有线(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>

您可以在示例中看到它是this codepen。尽管使用Guy L,kdedorov91和dauzduz TV答案中的方法,我极有可能使用div作为link。我建议这样做。当在控制台中以错误和警告消息的形式正确使用标签时,每个元素都将在页面中扮演角色,并且浏览器趋向于冒犯。如果您决定使用上述答案之一,请确保将role的{​​{1}}属性设置为div

相关问题