简体   繁体   English

单击锚点内的div时取消锚点

[英]Cancelling the anchor when clicking on a div inside the anchor

I have an anchor element in my html: 我的html中有一个锚元素:

<a class="info-tiles tiles-inverse has-footer" href="somepage.html?id=15">
  <div class="tiles-heading">
    <div class="pull-left">IT Department - Hosting environment</div>
  </div>
  <div class="tiles-body">
    <div class="nav-justified" style="font-size: small;">Started: 19-05-2015 07:00</div>
    <div class="btn btn-sm btn-default pull-right">AE</div>
    <div class="btn btn-sm btn-default pull-right">PJ</div>
    <div class="btn btn-sm btn-default pull-right">SL</div>
  </div>
  <div class="tiles-footer">
    <div class="progress">
      <div class="progress-bar progress-bar-info" style="width: 20%"></div>
    </div>
  </div>
</a>

This code renders like this: 此代码呈现如下:

示例渲染

The behavior is ok in general, that clicking on anywhere in this anchor should direct me to the another page, but I'd like to be able to click on those lightgrey tiles [SL][PL][AE] and display a context menu for those. 一般来说行为是可以的,点击这个锚点的任何地方都应该引导我到另一个页面,但是我希望能够点击那些光泽的瓷砖[SL] [PL] [AE]并显示一个上下文菜单对于那些。 What is a clean approach to change this behavior so that I still can click anywhere to navigate to the somepage.html, except if I click on those tiles, the navigation should not happen, and instead fire a javascript function (which would then display some context menu)? 什么是改变这种行为的干净方法,以便我仍然可以点击任何地方导航到somepage.html,除非我点击这些图块,导航不应该发生,而是激发一个javascript函数(然后会显示一些上下文菜单)?

If you use jQuery, you might want to take that approach: 如果您使用jQuery,您可能想采用这种方法:

$(".btn.btn-sm.pull-right").on("click", function(e) {
    e.stopPropagation();

    $(this).find(".context-menu").toggle();

    e.preventDefault();
    return false;
});

Then you'd need to write a 然后你需要写一个

<div class="context-menu">
    <ul>
        <li>Element</li>
    </ul>
</div>

and style it with basic css. 并用基本的CSS设计它。

Edit: To support older version of IE, you might also add that just after the e.stopPropagation(); 编辑:为了支持旧版本的IE,你也可以在e.stopPropagation()之后添加;

event.cancelBubble = true;

You can use stopPropagation event method: 您可以使用stopPropagation事件方法:

 $('selector').on('click', function(e)  {
      e.stopPropagation();
      e.preventDefault();
      // your actions 
 }); 

This allows you to stop bubbling from the button to outside, and prevent to execute the anchor event. 这允许您停止从按钮冒泡到外部,并阻止执行锚事件。 I add preventDefault() to avoid default button actions 我添加preventDefault()以避免默认按钮操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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