【问题标题】:Apply certain JS to specified class/IDs only仅将某些 JS 应用于指定的类/ID
【发布时间】:2014-01-13 23:13:21
【问题描述】:

我有一个用 JS 编写的游戏,并且有一些代码可以防止 用户无需拖动并突出显示游戏内的内容:

onSelectStart="return false;"
onMouseDown="return false;"
style="-moz-user-select: none; -khtml-user-select: none; user-select: none;"

我通常在 HTML 中单独将其应用于游戏中的特定元素, 但是当你为你想要的每个元素都拥有所有这些代码时,它看起来并不好 “不可选择”。

利用我对 JavaScript 的一点了解,我写了这样的东西:

$(".nonselect").Nonselectable();
function Nonselectable() {
    onSelectStart="return false;"
    onMouseDown="return false;"
    style="-moz-user-select: none; -khtml-user-select: none; user-select: none;"
}

然后将.nonselect 添加到我想要不可选的元素中。

但它不起作用。为什么它不起作用,我该怎么做?

【问题讨论】:

  • 为什么不在css中制作呢?
  • @k102 我不在 CSS 中这样做的原因是因为 onSelectStartonMouseDown 必须存在于 IE 中。我可以放弃 IE,但现在,我想让它适用于所有浏览器。
  • 您可以查看本教程来制作您自己的 jQuery 插件,您可以在其中为所选元素添加事件和样式learn.jquery.com/plugins/basic-plugin-creation

标签: javascript jquery craftyjs


【解决方案1】:

使用each() 函数

$(".nonselect").each(function(){
    $(this).selectstart(function(event){event.preventDefault();});
    $(this).mousedown(function(event){event.preventDefault();});
    $(this).css("-moz-user-select", "none");
    $(this).css("-khtml-user-select: none; user-select", "none;"
});

【讨论】:

  • 抱歉,前 2 个函数在放入 each() 时似乎不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 2014-08-15
  • 2019-06-09
  • 1970-01-01
相关资源
最近更新 更多