美文网首页基础知识
如何实现JS主动触发事件

如何实现JS主动触发事件

作者: mocobk | 来源:发表于2020-11-21 22:38 被阅读0次

    1. document.createEvent(eventType)

    参数:eventType 共5种类型:

    eventType 包含事件
    Events 包括所有的事件
    HTMLEvents abort, blur, change, error, focus, load, reset, resize, scroll,select, submit, unload
    UIEevents DOMActivate, DOMFocusIn, DOMFocusOut, keydown, keypress, keyup
    MouseEvents click, mousedown, mousemove, mouseout, mouseover, mouseup
    MutationEvents DOMAttrModified, DOMNodeInserted, DOMNodeRemoved, DOMCharacterDataModified, DOMNodeInsertedIntoDocument, DOMNodeRemovedFromDocument, DOMSubtreeModified

    document.createEvent后必须初始化才能触发

    // 通用 Events 和 HTMLEvents
    event.initEvent( 'type', bubbles, cancelable )
    // UIEvents
    event.initUIEvent( 'type', bubbles, cancelable, windowObject, detail )
    //MouseEvents
    event.initMouseEvent( 'type', bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget )
    //MutationEvents
    event.initMutationEvent( 'type', bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange ) 
    
    // 在目标元素上触发事件, 需要注意的是在IE 5.5+版本上请用fireEvent方法
    targetElement.dispatchEvent( event )
    

    举个栗子(主动触发 mouseover 事件)

    1. 主动触发 click 事件
    // 使用通用类型创建 click 事件
    const event = document.createEvent('Events');
    event.initEvent( 'click', true, false );
    const targetElement = document.getElementById('someID');
    targetElement.dispatchEvent(event);
    
    // 使用通 MouseEvents 创建 click 事件
    const event = document.createEvent('MouseEvents');
    event.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
    const targetElement = document.getElementById('someID');
    targetElement.dispatchEvent(event);
    
    1. 主动触发 mouseover 事件, 并考虑对 IE 的兼容
    const targetElement = document.getElementById('someID');
    
    if ( document.createEvent ) {
        const event = document.createEvent('MouseEvents');
        event.initEvent( 'mouseover', true, false );
        targetElement.dispatchEvent(event);
    }else if ( document.createEventObject ) {
        //兼容IE
        targetElement.fireEvent('onmouseover');
    }
    

    相关文章

      网友评论

        本文标题:如何实现JS主动触发事件

        本文链接:https://www.haomeiwen.com/subject/eglyiktx.html