Make a HTML link that does nothing (literally nothing)

前端 未结 9 591
耶瑟儿~
耶瑟儿~ 2020-12-13 23:35

I want a link that does nothing. I don\'t want this:

because then the URL becomes something.com/whatever/#.

相关标签:
9条回答
  • 2020-12-14 00:14

    In HTML5, this is very simple. Just omit the href attribute.

    <a>Do Nothing</a>

    From MDN on the a tag href attribute:

    href

    This was the single required attribute for anchors defining a hypertext source link, but is no longer required in HTML5.


    What about the hand cursor on hover?

    The default styles for a browser may not change the cursor to a pointer, for a tags with no href. You can universally change this with the following CSS.

    a {
        cursor: pointer;
    }
    <a>Do Nothing</a>

    However it's probably better to be more-selective about it, and apply it to only the elements you intend to add event handlers to.


    What about making it tab-focusable?

    Just add tabindex="0" to the element.

    <a tabindex="0">Do Nothing</a>


    Does it makes sense to use an a tag without a link?

    Usually no, it's probably better to use a button element instead, and style it with CSS. But whatever you use, avoid using an arbitrary element like div when possible, as this is not semantic at all.

    0 讨论(0)
  • 2020-12-14 00:14

    @Curt's answer will work, but you can use a cursor style in css to make it look like a link without the bother of generated a bogus link. Use hand or pointer depending on browser conformance.

    Cross browser conformant pointer css (from cursor style guide):

    element {
        cursor: pointer;
        cursor: hand;
    }
    
    0 讨论(0)
  • 2020-12-14 00:16

    Try this:

    <a href="javascript:void(0);">link</a>
    
    0 讨论(0)
提交回复
热议问题