使div可点击,但不要破坏嵌入式链接(一页上有多个div)

时间:2018-08-31 21:47:15

标签: html

我需要使div可点击,每个HTML5都足够简单:

<a href='#'>
  <div>Hello World</div>
</a>

我遇到的问题是我的一些div对象包含链接:

<div>Hello World. <a href='#'>Click me</a>

因此,只要有嵌入式链接,第一个示例中的方法就会中断。

<a href='#'>
  <div>Hello World  <a href='#'>Click me</a></div>
</a>
^^^^ already closed here ---------------^^^^

编辑:而且,一页上有多个div。每个div指向不同的URL。

有没有更好,更干净的方法来处理此问题,因此div中的空白是可单击的,但文本除外-可以是纯文本或链接,如我的第二个示例所示。

2 个答案:

答案 0 :(得分:2)

不是将您的div包裹在链接中,而是将事件监听器添加到div s中,以检查链接是否是事件目标:

// get a NodeList of all divs with the attribute data-url
// and destructure the NodeList to an Array using [...NodeList]
const divs = [...document.querySelectorAll('div[data-url]')];

// now that divs is an array we can use Array methods to iterate
for (const div of divs) {
  div.addEventListener('click', event => {
    switch (event.target.tagName) {
      case 'A':
        // do nothing
        break;
      default:
        // do whatever you want to do on div click here
        console.log(event.target.dataset.url);
        // this would be
        // location.href = event.target.dataset.url;
        // in your application
    }
  });
}
<div data-url="https://connexo.de/defuse">Hello World  <a href='#'>Click me</a></div>
<div data-url="http://example.com">Hello World  <a href='#'>Click me</a></div>

请注意,我的代码示例基于ES6语法。如果需要支持不了解ES6的浏览器,则需要Babel这样的编译器,或者需要将该代码重新编写为ES5。这是ES5中的相同示例:

// get a NodeList of all divs with the attribute data-url
var divs = document.querySelectorAll('div[data-url]');

// now use Array.prototype.forEach on the 
// NodeList using Function.prototype.call()
Array.prototype.forEach.call(divs, function(div) {
  div.addEventListener('click', function(event) {
    switch (event.target.tagName) {
      case 'A':
        // do nothing
        break;
      default:
        // do whatever you want to do on div click here
        console.log(event.target.dataset.url);
        // this would be
        // location.href = event.target.dataset.url;
        // in your application
    }
  });
})
<div data-url="https://connexo.de/defuse">Hello World  <a href='#'>Click me</a></div>
<div data-url="http://example.com">Hello World  <a href='#'>Click me</a></div>

答案 1 :(得分:0)

如果您需要容器充当链接并包含其他链接,则可以使用CSS来解决。

<style>
    .container { position: relative; }
    .back-layer { position: absolute; top: 0; right: 0; bottom: 0; left: 0; }
    .container p { position: relative; z-index: 1; }
</style>

<div class="container">
    <a class="back-layer" href="http://example.com"></a>
    <p>I am text with <a href="http://example.com">link.</a></p>
    <p>I am another paragraph with <a href="http://example.com">link</a>.</p>
</div>

.back-layer在相对定位的.container中“拉伸”。已将pz-index: 1分配到.back-layer的顶部。

如果您的链接是真实链接,则此方法不需要任何JavaScript,并且可能在语义上对您更有效。