如何将div标签转换为链接

时间:2022-06-29 23:47:55

How do you make a div tag into a link. I would like my entire div to be clickable.

如何将div标签转换为链接。我希望我的整个div都可以点击。

10 个解决方案

#1


15  

JS:

<div onclick="location.href='url'">content</div>

jQuery:

$("div").click(function(){
   window.location=$(this).find("a").attr("href"); return false;
});

Make sure to use cursor:pointer for these DIVs

确保对这些DIV使用cursor:pointer

#2


11  

If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.

如果你必须在div中设置你的锚标签,你也可以使用CSS来设置锚点以通过display:block填充div。

As such:

<div style="height: 80px"><a href="#" style="display: block">Text</a></div>

Now when the user floats their cursor in that div the anchor tag will fill the div.

现在,当用户将光标悬浮在该div中时,锚标记将填充div。

#3


10  

If you're using HTML5, as pointed in this other question, you can put your div inside a:

如果你正在使用HTML5,正如另一个问题所指出的那样,你可以把你的div放在:

<a href="http://www.google.com"><div>Some content here</div></a>

Preffer this method as it makes clear in your structure that all the content is clickable, and where it's pointing.

提供此方法,因为它在您的结构中明确了所有内容都是可点击的,以及它指向的位置。

#4


7  

DON'T DO IT.

不要那样做。

  • If you want a link, wrap the content in the proper <A>NCHOR</a>.
  • 如果您需要链接,请将内容包装在正确的 NCHOR 中。

  • If you want to turn the <DIV> into a link, use "Javascript" to wrap the <DIV> inside an <A>NCHOR</A>
  • 如果您想将

    转换为链接,请使用“Javascript”将
    包裹在 NCHOR

  • If you want to perform some action when clicking the <DIV> use the onclick event handler... and don't call it a "link".
  • 如果要在单击

    时执行某些操作,请使用onclick事件处理程序...并且不要将其称为“链接”。

#5


7  

So you want an element to be something it's not?

所以你想要一个元素不是它的东西?

Generally speaking this isn't a good idea. If you need a link, use a link. Most of the time it's easier to just use the appropriate markup where it belongs.

一般来说,这不是一个好主意。如果您需要链接,请使用链接。大多数情况下,只使用它所属的适当标记会更容易。

That all said, sometimes you just have to break the rules. Now, the question doesn't have , so I'm going to put the disclaimer here:

所有人都说,有时你只需打破规则。现在,这个问题没有javascript,所以我要把免责声明放在这里:

You can't have a <div> act as a link without either using a link (or equivalent, such as a <form> that only contains a submit button) or using JavaScript.

如果没有使用链接(或等效的链接,例如只包含提交按钮的

)或使用JavaScript,则不能将
作为链接。

From here on out, this answer is going to assume that JavaScript is allowed, and furthermore that jQuery is being used (for brevity of example).

从现在开始,这个答案将假设允许使用JavaScript,而且还使用了jQuery(为了简洁起见)。

With that all said, lets dig into what makes a link a link.

有了这一切,让我们深入了解链接的链接。


Links are generally elements that you click on so that they navigate you to a new document.

链接通常是您单击的元素,以便它们导航到新文档。

It seems simple enough. Listen for a click event and change the location:

看起来很简单。收听点击事件并更改位置:

Don't do this

$('.link').on('click', function () {
  window.location = 'http://example.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">Fake Link</div>

There you have it, the <div> is now a link. Wait...what's that? What about accessibility? Oh right, screen readers and users of assistive technology won't be able to click on the link, especially if they're only using the keyboard.

你有它,

现在是一个链接。等等......那是什么?可访问性怎么样?哦,对,屏幕阅读器和辅助技术的用户将无法点击链接,特别是如果他们只使用键盘。

Fixing that's pretty simple, let's allow keyboard only users to focus the <div>, and trigger the click event when they press Enter:

修复这很简单,让我们只允许键盘用户聚焦

,并在按Enter键时触发click事件:

Don't do this either

$('.link').on({
  'click': function () {
    window.location = 'http://example.com';
  },
  'keydown': function (e) {
    if (e.which === 13) {
      $(this).trigger('click');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link" tabindex="0">Fake Link</div>

Again, there you have it, this <div> is now a link. Wait...again? Still accessibility problems? Oh ok, so it turns out that the assistive technology doesn't know that the <div> is a link yet, so even though you can get there via keyboard, users aren't being told what to do with it.

再次,你有它,这个

现在是一个链接。等待......再?还是可访问性问题?哦,好吧,事实证明,辅助技术还不知道
是一个链接,所以即使你可以通过键盘到达那里,用户也不会被告知如何处理它。

Fortunately, there's an attribute that can be used to override an HTML element's default role, so that screen readers and the like know how to categorize customized elements, like our <div> here. The attribute is of course the [role] attribute, and it nicely tells screen readers that our <div> is a link:

幸运的是,有一个属性可用于覆盖HTML元素的默认角色,因此屏幕阅读器等知道如何对自定义元素进行分类,例如我们的

。该属性当然是[role]属性,它很好地告诉屏幕读者我们的
是一个链接:

Ugh, this is getting worse every minute

$('[role="link"]').on({
  'click': function () {
    window.location = 'http://example.com';
  },
  'keydown': function (e) {
    if (e.which === 13) {
      $(this).trigger('click');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0">Fake Link</div>

Finally, our <div> is a lin---oh now the other devs are complaining. What now?

最后,我们的

是林---哦,现在其他开发者都在抱怨。现在怎么办?

Ok, so the devs don't like the code. They tried to preventDefault on the event, and it just keeps working. That's easy to fix:

好的,所以开发人员不喜欢这些代码。他们试图阻止对事件的默认,它只是继续工作。这很容易解决:

I warned you this was bad

$(document).on({
  'click': function (e) {
    if (!e.isDefaultPrevented()) {
      window.location = 'http://example.com';
    }
  },
  'keydown': function (e) {
    if (e.which === 13 && !e.isDefaultPrevented()) {
      $(this).trigger('click');
    }
  }
}, '[role="link"]');

$('[aria-disabled="true"]').on('click', function (e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0">Fake Link</div>
<div role="link" aria-disabled="true" tabindex="0">Fake disabled link</div>

There we have it---THERE'S MORE? What else don't I know? Tell me everything NOW so that I can fix it!

我们有它 - 还有更多?还有什么我不知道的?现在告诉我一切,以便我可以解决它!

  • Ok, so there's no way to specify target. We can fix that by updating to window.open.
  • 好的,所以没有办法指定目标。我们可以通过更新到window.open来解决这个问题。

  • Click events and keyboard events are ignoring Ctrl, Alt, and Shift keys. That's easy enough, just need to check those values on the event object.
  • 单击事件和键盘事件忽略Ctrl,Alt和Shift键。这很容易,只需要检查事件对象上的那些值。

  • There's no way to specify contextual data. Let's just add some [data-*] attributes, and call it a day with that one.
  • 无法指定上下文数据。让我们添加一些[data- *]属性,然后用它来调用它。

  • The click event isn't obeying the mouse button that's being used, middle mouse should open in a new tab, right mouse shouldn't be triggering the event. Easy enough, just add some more checks to the event listeners.
  • click事件不遵循正在使用的鼠标按钮,鼠标中键应该在新选项卡中打开,右键不应该触发事件。很容易,只需要为事件监听器添加一些检查。

  • The styles look weird. WELL OF COURSE THE STYLES ARE WEIRD, IT'S A <DIV> NOT AN ANCHOR!
  • 风格看起来很奇怪。课程很好,风格很吵,是

    不是主持人!

well, I'll address the first four issues, and NO MORE. I've had it with this stupid custom element garbage. I should have just used an <a> element from the beginning.

好吧,我将解决前四个问题,而不是更多。我已经用这个愚蠢的自定义元素垃圾了。我应该从一开始就使用元素。

Told you so

$(document).on({
  'click': function (e) {
    var target,
        href;
    if (!e.isDefaultPrevented() && (e.which === 1 || e.which === 2)) {
      target = $(this).data('target') || '_self';
      href = $(this).data('href');
      if (e.ctrlKey || e.shiftKey || e.which === 2) {
        target = '_blank'; //close enough
      }
      open(href, target);
    }
  },
  'keydown': function (e) {
    if (e.which === 13 && !e.isDefaultPrevented()) {
      $(this).trigger({
        type: 'click',
        ctrlKey: e.ctrlKey,
        altKey: e.altKey,
        shiftKey: e.shiftKey
      });
    }
  }
}, '[role="link"]');

$('[aria-disabled="true"]').on('click', function (e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0" data-href="http://example.com/">Fake Link</div>
<div role="link" tabindex="0" data-href="http://example.com/" data-target="_blank">Fake Link With Target</div>
<div role="link" aria-disabled="true" tabindex="0" data-href="http://example.com/">Fake disabled link</div>

Note that stack snippets won't open popup windows because of how they're sandboxed.

请注意,堆栈片段不会打开弹出窗口,因为它们是如何沙箱化的。

That's it. That's the end of this rabbit hole. All of that craziness when you could have simply had:

而已。这就是这个兔子洞的终点。所有这些疯狂,当你可能只是:

<a href="http://example.com/">
    ...your markup here...
</a>

The code I posted here probably has problems. It probably has bugs that even I don't realize as of yet. Trying to duplicate what browsers give you for free is tough. There are so many nuances that are easy to overlook that it's simply not worth trying to emulate it 99% of the time.

我在这里发布的代码可能有问题。它可能有一些甚至我还没有意识到的错误。试图复制哪些浏览器免费提供给您是很困难的。有很多细微差别很容易被忽视,因此在99%的情况下尝试模仿它是不值得的。

#6


5  

<div style="cursor:pointer" onclick="document.location='http://www.google.com'">Content Goes Here</div>

#7


2  

<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>

#8


2  

You can make the entire DIV function as a link by adding an onclick="window.location='TARGET URL'" and by setting its style to "cursor:pointer". But it's often a bad idea to do this because search engines won't be able to follow the resulting link, readers won't be able to open in tabs or copy the link location, etc. Instead, you can create a regular anchor tag and then set its style to display:block , and then style this as you would a DIV.

您可以通过添加onclick =“window.location ='TARGET URL'”并将其样式设置为“cursor:pointer”,将整个DIV函数作为链接。但这样做通常是一个坏主意,因为搜索引擎无法跟踪生成的链接,读者将无法在标签中打开或复制链接位置等。相反,您可以创建常规锚标记然后将其样式设置为display:block,然后像DIV那样设置样式。

#9


2  

You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:

您可以使用Javascript来实现此效果。如果你使用框架,这种事情变得非常简单。这是jQuery中的一个例子:

$('div#id').click(function (e) {
  // Do whatever you want
});

This solution has the distinct advantage of keeping the logic not in your markup.

此解决方案具有保持逻辑不在您的标记中的独特优势。

#10


0  

Keep in mind that search spiders don't index JS code. So if you put your URL inside JS code, be sure to also include it in a traditional HTML link elsewhere on the page. That is, if you want the linked pages to be indexed by Google, etc.

请记住,搜索蜘蛛不会索引JS代码。因此,如果您将URL放在JS代码中,请确保将其包含在页面上其他位置的传统HTML链接中。也就是说,如果您希望链接的网页被Google等编入索引。

#1


15  

JS:

<div onclick="location.href='url'">content</div>

jQuery:

$("div").click(function(){
   window.location=$(this).find("a").attr("href"); return false;
});

Make sure to use cursor:pointer for these DIVs

确保对这些DIV使用cursor:pointer

#2


11  

If you have to set your anchor tag inside the div, you can also use CSS to set the anchor to fill the div via display:block.

如果你必须在div中设置你的锚标签,你也可以使用CSS来设置锚点以通过display:block填充div。

As such:

<div style="height: 80px"><a href="#" style="display: block">Text</a></div>

Now when the user floats their cursor in that div the anchor tag will fill the div.

现在,当用户将光标悬浮在该div中时,锚标记将填充div。

#3


10  

If you're using HTML5, as pointed in this other question, you can put your div inside a:

如果你正在使用HTML5,正如另一个问题所指出的那样,你可以把你的div放在:

<a href="http://www.google.com"><div>Some content here</div></a>

Preffer this method as it makes clear in your structure that all the content is clickable, and where it's pointing.

提供此方法,因为它在您的结构中明确了所有内容都是可点击的,以及它指向的位置。

#4


7  

DON'T DO IT.

不要那样做。

  • If you want a link, wrap the content in the proper <A>NCHOR</a>.
  • 如果您需要链接,请将内容包装在正确的 NCHOR 中。

  • If you want to turn the <DIV> into a link, use "Javascript" to wrap the <DIV> inside an <A>NCHOR</A>
  • 如果您想将

    转换为链接,请使用“Javascript”将
    包裹在 NCHOR

  • If you want to perform some action when clicking the <DIV> use the onclick event handler... and don't call it a "link".
  • 如果要在单击

    时执行某些操作,请使用onclick事件处理程序...并且不要将其称为“链接”。

#5


7  

So you want an element to be something it's not?

所以你想要一个元素不是它的东西?

Generally speaking this isn't a good idea. If you need a link, use a link. Most of the time it's easier to just use the appropriate markup where it belongs.

一般来说,这不是一个好主意。如果您需要链接,请使用链接。大多数情况下,只使用它所属的适当标记会更容易。

That all said, sometimes you just have to break the rules. Now, the question doesn't have , so I'm going to put the disclaimer here:

所有人都说,有时你只需打破规则。现在,这个问题没有javascript,所以我要把免责声明放在这里:

You can't have a <div> act as a link without either using a link (or equivalent, such as a <form> that only contains a submit button) or using JavaScript.

如果没有使用链接(或等效的链接,例如只包含提交按钮的

)或使用JavaScript,则不能将
作为链接。

From here on out, this answer is going to assume that JavaScript is allowed, and furthermore that jQuery is being used (for brevity of example).

从现在开始,这个答案将假设允许使用JavaScript,而且还使用了jQuery(为了简洁起见)。

With that all said, lets dig into what makes a link a link.

有了这一切,让我们深入了解链接的链接。


Links are generally elements that you click on so that they navigate you to a new document.

链接通常是您单击的元素,以便它们导航到新文档。

It seems simple enough. Listen for a click event and change the location:

看起来很简单。收听点击事件并更改位置:

Don't do this

$('.link').on('click', function () {
  window.location = 'http://example.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link">Fake Link</div>

There you have it, the <div> is now a link. Wait...what's that? What about accessibility? Oh right, screen readers and users of assistive technology won't be able to click on the link, especially if they're only using the keyboard.

你有它,

现在是一个链接。等等......那是什么?可访问性怎么样?哦,对,屏幕阅读器和辅助技术的用户将无法点击链接,特别是如果他们只使用键盘。

Fixing that's pretty simple, let's allow keyboard only users to focus the <div>, and trigger the click event when they press Enter:

修复这很简单,让我们只允许键盘用户聚焦

,并在按Enter键时触发click事件:

Don't do this either

$('.link').on({
  'click': function () {
    window.location = 'http://example.com';
  },
  'keydown': function (e) {
    if (e.which === 13) {
      $(this).trigger('click');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link" tabindex="0">Fake Link</div>

Again, there you have it, this <div> is now a link. Wait...again? Still accessibility problems? Oh ok, so it turns out that the assistive technology doesn't know that the <div> is a link yet, so even though you can get there via keyboard, users aren't being told what to do with it.

再次,你有它,这个

现在是一个链接。等待......再?还是可访问性问题?哦,好吧,事实证明,辅助技术还不知道
是一个链接,所以即使你可以通过键盘到达那里,用户也不会被告知如何处理它。

Fortunately, there's an attribute that can be used to override an HTML element's default role, so that screen readers and the like know how to categorize customized elements, like our <div> here. The attribute is of course the [role] attribute, and it nicely tells screen readers that our <div> is a link:

幸运的是,有一个属性可用于覆盖HTML元素的默认角色,因此屏幕阅读器等知道如何对自定义元素进行分类,例如我们的

。该属性当然是[role]属性,它很好地告诉屏幕读者我们的
是一个链接:

Ugh, this is getting worse every minute

$('[role="link"]').on({
  'click': function () {
    window.location = 'http://example.com';
  },
  'keydown': function (e) {
    if (e.which === 13) {
      $(this).trigger('click');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0">Fake Link</div>

Finally, our <div> is a lin---oh now the other devs are complaining. What now?

最后,我们的

是林---哦,现在其他开发者都在抱怨。现在怎么办?

Ok, so the devs don't like the code. They tried to preventDefault on the event, and it just keeps working. That's easy to fix:

好的,所以开发人员不喜欢这些代码。他们试图阻止对事件的默认,它只是继续工作。这很容易解决:

I warned you this was bad

$(document).on({
  'click': function (e) {
    if (!e.isDefaultPrevented()) {
      window.location = 'http://example.com';
    }
  },
  'keydown': function (e) {
    if (e.which === 13 && !e.isDefaultPrevented()) {
      $(this).trigger('click');
    }
  }
}, '[role="link"]');

$('[aria-disabled="true"]').on('click', function (e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0">Fake Link</div>
<div role="link" aria-disabled="true" tabindex="0">Fake disabled link</div>

There we have it---THERE'S MORE? What else don't I know? Tell me everything NOW so that I can fix it!

我们有它 - 还有更多?还有什么我不知道的?现在告诉我一切,以便我可以解决它!

  • Ok, so there's no way to specify target. We can fix that by updating to window.open.
  • 好的,所以没有办法指定目标。我们可以通过更新到window.open来解决这个问题。

  • Click events and keyboard events are ignoring Ctrl, Alt, and Shift keys. That's easy enough, just need to check those values on the event object.
  • 单击事件和键盘事件忽略Ctrl,Alt和Shift键。这很容易,只需要检查事件对象上的那些值。

  • There's no way to specify contextual data. Let's just add some [data-*] attributes, and call it a day with that one.
  • 无法指定上下文数据。让我们添加一些[data- *]属性,然后用它来调用它。

  • The click event isn't obeying the mouse button that's being used, middle mouse should open in a new tab, right mouse shouldn't be triggering the event. Easy enough, just add some more checks to the event listeners.
  • click事件不遵循正在使用的鼠标按钮,鼠标中键应该在新选项卡中打开,右键不应该触发事件。很容易,只需要为事件监听器添加一些检查。

  • The styles look weird. WELL OF COURSE THE STYLES ARE WEIRD, IT'S A <DIV> NOT AN ANCHOR!
  • 风格看起来很奇怪。课程很好,风格很吵,是

    不是主持人!

well, I'll address the first four issues, and NO MORE. I've had it with this stupid custom element garbage. I should have just used an <a> element from the beginning.

好吧,我将解决前四个问题,而不是更多。我已经用这个愚蠢的自定义元素垃圾了。我应该从一开始就使用元素。

Told you so

$(document).on({
  'click': function (e) {
    var target,
        href;
    if (!e.isDefaultPrevented() && (e.which === 1 || e.which === 2)) {
      target = $(this).data('target') || '_self';
      href = $(this).data('href');
      if (e.ctrlKey || e.shiftKey || e.which === 2) {
        target = '_blank'; //close enough
      }
      open(href, target);
    }
  },
  'keydown': function (e) {
    if (e.which === 13 && !e.isDefaultPrevented()) {
      $(this).trigger({
        type: 'click',
        ctrlKey: e.ctrlKey,
        altKey: e.altKey,
        shiftKey: e.shiftKey
      });
    }
  }
}, '[role="link"]');

$('[aria-disabled="true"]').on('click', function (e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="link" tabindex="0" data-href="http://example.com/">Fake Link</div>
<div role="link" tabindex="0" data-href="http://example.com/" data-target="_blank">Fake Link With Target</div>
<div role="link" aria-disabled="true" tabindex="0" data-href="http://example.com/">Fake disabled link</div>

Note that stack snippets won't open popup windows because of how they're sandboxed.

请注意,堆栈片段不会打开弹出窗口,因为它们是如何沙箱化的。

That's it. That's the end of this rabbit hole. All of that craziness when you could have simply had:

而已。这就是这个兔子洞的终点。所有这些疯狂,当你可能只是:

<a href="http://example.com/">
    ...your markup here...
</a>

The code I posted here probably has problems. It probably has bugs that even I don't realize as of yet. Trying to duplicate what browsers give you for free is tough. There are so many nuances that are easy to overlook that it's simply not worth trying to emulate it 99% of the time.

我在这里发布的代码可能有问题。它可能有一些甚至我还没有意识到的错误。试图复制哪些浏览器免费提供给您是很困难的。有很多细微差别很容易被忽视,因此在99%的情况下尝试模仿它是不值得的。

#6


5  

<div style="cursor:pointer" onclick="document.location='http://www.google.com'">Content Goes Here</div>

#7


2  

<div style="cursor:pointer;" onclick="document.location='http://www.google.com'">Foo</div>

#8


2  

You can make the entire DIV function as a link by adding an onclick="window.location='TARGET URL'" and by setting its style to "cursor:pointer". But it's often a bad idea to do this because search engines won't be able to follow the resulting link, readers won't be able to open in tabs or copy the link location, etc. Instead, you can create a regular anchor tag and then set its style to display:block , and then style this as you would a DIV.

您可以通过添加onclick =“window.location ='TARGET URL'”并将其样式设置为“cursor:pointer”,将整个DIV函数作为链接。但这样做通常是一个坏主意,因为搜索引擎无法跟踪生成的链接,读者将无法在标签中打开或复制链接位置等。相反,您可以创建常规锚标记然后将其样式设置为display:block,然后像DIV那样设置样式。

#9


2  

You could use Javascript to achieve this effect. If you use a framework this sort of thing becomes quite simple. Here is an example in jQuery:

您可以使用Javascript来实现此效果。如果你使用框架,这种事情变得非常简单。这是jQuery中的一个例子:

$('div#id').click(function (e) {
  // Do whatever you want
});

This solution has the distinct advantage of keeping the logic not in your markup.

此解决方案具有保持逻辑不在您的标记中的独特优势。

#10


0  

Keep in mind that search spiders don't index JS code. So if you put your URL inside JS code, be sure to also include it in a traditional HTML link elsewhere on the page. That is, if you want the linked pages to be indexed by Google, etc.

请记住,搜索蜘蛛不会索引JS代码。因此,如果您将URL放在JS代码中,请确保将其包含在页面上其他位置的传统HTML链接中。也就是说,如果您希望链接的网页被Google等编入索引。