使用javascript防止标签活动状态

时间:2017-05-16 19:15:16

标签: javascript html css

我有一个非常simple scenario,我试图阻止鼠标按下橙色背景:



document.querySelector('label').addEventListener('mousedown', (event) => {
  console.log('mouse down') 
  event.preventDefault();
})

label:active {
  background: orange;
}

<label>Press mouse down</label>
&#13;
&#13;
&#13;

不幸的是,event.preventDefault()没有效果,标签变为橙色。 (在Chrome和Safari和IE11中测试过)

Label Bug Demo

任何人都可以解释我背后的原因,或者告诉我如何在没有黑客攻击的情况下以编程方式阻止活动状态?

Codepen:https://codepen.io/anon/pen/pPZVrO

2 个答案:

答案 0 :(得分:5)

It seems like an old issue。如果需要,可以使用pointer-events属性进行修复。此外,相同的support非常不错(包括IE11)

label:active {
  background: orange;
}

label {
  pointer-events: none;
}
<label>Press mouse down</label>

确保您在class元素上声明了一些idlabel,这样您就无法定位所有这些元素。

JavaScript解决方案 - 只是试一试

我们的想法是在class上添加mousedown,并使用class:active的CSS class覆盖它,然后删除{在class上{1}},例如

mouseup
var overrideActive = function() {
  var labelElm = document.querySelector('label');
  var bodyElm = document.querySelector('body');

  function init() {
    //on mousedown, add a class and override it with css
    labelElm.addEventListener('mousedown', (event) => {
      event.target.className = 'disable-active';
    });

    //onmouseout get rid of the class
    bodyElm.addEventListener('mouseup', (event) => {
      labelElm.classList.remove('disable-active');
    });
  }

  return {
    init: init
  }
}();

overrideActive.init();
label:active {
  background: orange;
}

.disable-active:active {
  background-color: transparent;
}

答案 1 :(得分:0)

您可以通过css禁用鼠标事件。添加此CSS将阻止背景变为橙色。

label {
  pointer-events: none;
}

如果您不想在每种情况下都这样做,请使用类并仅在需要时应用noclick类(即,作为部分反应的render()方法,或者在生成页面时,取决于在你正在使用的框架上。

.noclick {
  pointer-events: none;
}