部分jquery代码修改为原生js

1、.css => .style

$('#searchBox').css({'display': 'none'})
document.getElementById('searchBox').style.display = 'none'

2、禁止右键点击事件 contextmenu

$('img').bind("contextmenu", function(e){ return false; });
$('video').bind("contextmenu", function(e){ return false; });
//右键
document.addEventListener('contextmenu', function (e) {
      e.preventDefault();
});

https://blog.csdn.net/tianpeng1996/article/details/107993435

3、点击某个div以外的区域,执行点击事件

         let that = this
        $('#home').bind('click', function (e) { // $('#home'),指的是在这个区域内执行
            var o = e.target;
            if($(o).closest('#patientBox').length==0) { // 点击id不是patientBox的区域,执行以下事件
                document.getElementById('searchBox').style.display = 'none'
            }
        })
// 类似jquery closest方法
        function closest ( selectors, context ) {
            var cur,
                i = 0,
                l = this.length,
                matched = [],
                pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
                    jQuery( selectors, context || this.context ) :
                    0;
            for ( ; i < l; i++ ) {
                for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
                    // Always skip document fragments
                    if ( cur.nodeType < 11 && ( pos ?
                        pos.index( cur ) > -1 :
                        // Don't pass non-elements to Sizzle
                        cur.nodeType === 1 &&
                            jQuery.find.matchesSelector( cur, selectors ) ) ) {
                        matched.push( cur );
                        break;
                    }
                }
            }
            return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
        }

        let home = document.getElementById('home')
        home.addEventListener('click', function(e) {
            var el = e.target
            if(!el.closest('.search_box')) { // 父级元素不存在某个class,即点击不是该元素内,执行该方法
                document.getElementById('searchBox').style.display = 'none'  
            }
        })

引入:http://printf.cn/index.php/archives/96.html
原生js closest:https://segmentfault.com/q/1010000007921194

你可能感兴趣的:(部分jquery代码修改为原生js)