简体   繁体   中英

How do I make <a> tags with a class unclickable?

I have some parent nav items with children and I don't need the parent items to be clickable.

They look like this:

<a href="parent">Parent Item</a>

Is there anyway to target the <a> tags with the specific class of .parent and make them unclickable?

If anyone interested in Pure CSS solution (As this question is tagged as CSS) than you can use pointer-events: none;

a[href="parent"] {
    cursor: default;
    pointer-events: none;
}

Demo


As far as support goes

在此处输入图片说明

Credits: Mozilla Developer Network

Use:

  $(function () {
    $('a.parent').on("click", function (e) {
      e.preventDefault();
    });
});

If you want to avoid using the jQuery library, it's just as easy without it:

var disabled = document.querySelector('.parent');
disabled.addEventListener('click', function(e) {e.preventDefault();}, false);

Another pure CSS option would be to overlay the link with an absolutely positioned "cover":

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style media="all">

.parent {position: relative; z-index: -1;}
.parent:after {content: ""; position: absolute; top:0; right: 0; bottom: 0; left: 0;}

</style>
</head>
<body>

<a href="http://google.com" class="parent">Disabled Link</a>
<a href="http://google.com">Normal Link</a>

</body>
</html>

Instead of a listener on every .parent , you can put a single listener on the body. The following will work in every browser in use without any library support:

function stopClickOnParentClass(evt) {
  var el = evt.target || evt.srcElement;
  if (/(^|\s)parent(\s|$)/.test(el.className)) {
    evt.preventDefault();
    return false;
  }
}

then:

<body onclick="stopClickOnParent(event);" …>

You could also make the class dynamic by passing it to the function and building the regular expression from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM