簡體   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