我可以帮您翻译成中文。问题是:链接是否可以有一个不可点击的部分?

3
希望这个问题简单明了。在下面的例子中,我希望链接的蓝色部分可以被点击(作为链接),但是红色部分不行。我计划在之后使用JavaScript订阅红色部分的onclick事件。

我花了一个小时却一无所获!有人知道怎么做吗?

.outer{
    width:300px;
    height:50px;
    background-color:blue;
    position:relative;
    display:block;
    color:white;
    z-index:1;
}

.inner{
    width:150px;
    height:25px;
    background-color:red;
    top:0;
    right:0;
    position:absolute;
    pointer-events:none;
    z-index:2;
}
<a href="http://google.co.uk" class="outer">
    Clickable
    <div class="inner">
        Not clickable
    </div>
</a>

我认为把内部的div设置为更高的z-index并且没有指针事件可以解决问题,但似乎不起作用。

有人有什么想法吗?


6
既然你已经在红色区域添加了JS,那么只需将event.preventDefault()添加到你的监听器中即可。 - Jonathan
@Jonathan 很好的建议,但我还是选择纯HTML/CSS的解决方案,谢谢。 - JMK
2个回答

7

不要像那样破解 html,这是一个非常糟糕的做法。为什么不尝试这样做:

.outer {
  background-color: red;
  display: inline-block;
}

.inner {
  background-color: blue;
  width: 300px;
  display: inline-block;
}

span {
  display: inline-block;
}
<div class="inner">
  <a href="http://google.co.uk" class="outer">Clickable</a>
  <span>Not clickable</span>
</div>


1
这应该是有用的。HTML5并不介意,但在我看来,这仍然是一种不好的做法。https://dev59.com/RnI-5IYBdhLWcg3wfoa1 - Vlad

4

使用 preventDefault 方法。

$('.inner').click(function(e){

e.preventDefault();


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<a href="http://google.co.uk" class="outer">
    Clickable
    <div class="inner">
        Not clickable
    </div>
</a>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接