将jQuery侦听器应用于元素'的孩子

Applying jQuery listeners to element's children

本文关键字:孩子 元素 jQuery 侦听器 应用于      更新时间:2023-09-26

我有一个带有jQuery contextmenu侦听器的按钮。

在Safari和Chrome浏览器中,右键单击按钮时,背景会变为蓝色一秒钟,然后按钮内的文本会被选中/高亮显示。

我该如何防止这种情况发生?

jQuery(".class1").contextmenu(function (e) {
    return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1">Click Me</button>

如果问题是在按钮内选择文本,那么您可以将noselect类添加到按钮中,不需要使用js。但也许我错了。

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* Internet Explorer/Edge */
  user-select: none;           /* Non-prefixed version, currently
                                  not supported by any browser */
}

.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* Internet Explorer/Edge */
  user-select: none;           /* Non-prefixed version, currently
                                  not supported by any browser */
}
/*maybe give it a static background .. */
button{
  background:yellow;
}
button:active{
  background:yellow!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1 noselect">Click Me</button>

在你提到你在Mac上的评论中,蓝色背景/边框可能是因为你使用CTRL+LMB点击。

当按下CTRL时,这将删除按钮上的焦点:

jQuery(".class1").contextmenu(function(e) {
    return false;
}).keydown(function(e) {
  if (e.keyCode == 17) { //CTRL
    $(this).blur();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class1">Click Me</button>