如何让:: before伪类可点击之前的SVG?

时间:2019-03-06 20:32:09

标签: svg breadcrumbs pseudo-class

我有一个面包屑,列出了页面的层次结构路径。我隐藏了第一个锚标签,并将锚标签::before伪类更改为小房子的SVG,如下所示:

li:first-child a {
    display: none;
  }

li:first-child::before {
    color: transparent;
    content: '';
    display: block;
    width: rem(16px);
    height: rem(16px);
    position: relative;
    top: rem(2px);
    margin: 0;
    background-image: url("../images/breadcrumb-image.svg");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    &:hover {
      color: transparent;
    }
  }

我获得了期望的效果,但是无法单击SVG返回到主页。有什么解决办法吗?我不在乎CSS还是JS。

这是图像,它给您一个想法: enter image description here

谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了一种使::before伪类上的SVG通过jQuery可单击的方法,如下所示:

SCSS代码:

这是隐藏锚标记并在伪类之前将SVG添加到锚标记的样式。

li:first-child a {
    display: none;
  }
li:first-child::before {
    color: transparent;
    content: '';
    cursor: pointer;
    display: block;
    width: rem(16px);
    height: rem(16px);
    position: relative;
    top: rem(2px);
    margin: 0;
    background-image: url("../images/breadcrumb-image.svg");
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    &:hover {
      color: transparent;
      cursor: pointer;
    }
  }

JavaScript代码:

  //Store the href attribute(the link was already pointing to the home page) of the anchor tag in a variable
  var breadcrumbHomeLink = $('.breadcrumb__list--item:first-child a').attr('href');

  //Store the SVG with ::before pseudo-class in variable
  var breadcrumbSVG = $('.breadcrumb__list--item:first-child').before();

  //Make Breadcrumb SVG clickable & redirect to home page
  breadcrumbSVG.on('click', function(){
    location.href = breadcrumbHomeLink;
  });