【问题标题】:The event of the document is not triggered, when it is on a disabled element当文档位于禁用元素上时,不会触发文档的事件
【发布时间】:2020-09-16 18:28:24
【问题描述】:

当我给文档一个mouseup 事件时,如果鼠标在一个禁用的元素中并且我释放了按钮。文档mouseup 事件处理程序无法触发。 我应该如何让处理程序被调用?

例子:

document.addEventListener('mouseup', () => {
  console.log('mouseup')
}, true)

const changeBtn = document.getElementById('change')
const testBtn = document.getElementById('test')

changeBtn.onclick = () => {
  testBtn.setAttribute('disabled', true)
}
testBtn.onclick = () => {
  console.log('testBtn click')
}
<button id="test">test</button>
<button id="change">change</button>

【问题讨论】:

    标签: javascript html dom frontend dom-events


    【解决方案1】:

    :disabled 元素上使用 CSS 集 pointer-events: none

    document.addEventListener('mouseup', () => {
      console.log('mouseup')
    }, true)
    
    const changeBtn = document.getElementById('change')
    const testBtn = document.getElementById('test')
    
    changeBtn.onclick = () => {
      testBtn.setAttribute('disabled', true)
    }
    testBtn.onclick = () => {
      console.log('testBtn click')
    }
    *:disabled {
      pointer-events: none;
    }
    <button id="test">test</button>
    <button id="change">change</button>

    【讨论】:

    • 谢谢,但还有其他方法吗?我可能不希望它触发冒泡或捕获,它的副作用一定太大了
    • 使用pointer-events: none 使元素对鼠标事件透明。如果您不想使用捕获,请不要将true 设置为addEventListener 的第二个参数。
    • 我只是想让文档触发事件。我不希望他的父元素触发事件,但是使用pointer-events: none会导致父元素也触发事件。我把addEventListener的第三个属性设置为false,但是事件的父元素还是会触发
    • 这是一个棘手的问题。您可以使用.closest() 向父事件处理程序添加一个排除禁用的禁用元素或其子元素的检查。
    猜你喜欢
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2013-08-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多