简体   繁体   English

将JavaScript附加到主体标签

[英]Attach JavaScript to body tag

Okay so i made drop down menu and i want it to be closed whenever user clicks anywhere at body.for this i need to attach some java Script code to body tag. 好的,所以我创建了下拉菜单,并且希望用户每次在body.click处单击时都将其关闭。为此,我需要在body标签上附加一些Java脚本代码。 i'm new to JavaScript and i have no idea how to do this. 我是JavaScript新手,我不知道该怎么做。 Is this even possible? 这有可能吗?

By the way, I found way of doing this with Jquery but i don't want to use it. 顺便说一句,我找到了使用Jquery做到这一点的方法,但我不想使用它。

also giving me an example will be really useful. 也给我一个例子会非常有用。

thanks. 谢谢。

(ignore) (忽视)

<script>
function show_menu(){
    var menu = document.getElementById('dropdown_menu');

    if(menu.style.display == 'block'){
        menu.style.display = 'none';
    }else {
        menu.style.display = 'block';                    
    }
}
</script>

addEventListener is a method on every element (among a few other things) and is the standard way to make a function run when "something" happens. addEventListener是每个元素上的方法(除其他外),并且是在发生“某些情况”时使函数运行的标准方法。

Call it on the body element, telling it what sort of event you want to react to and what function you want to run. 在body元素上调用它,告诉它您要响应哪种事件以及要运行什么函数。

document.body.addEventListener('click', show_menu);

Here's the basic idea. 这是基本思想。 Hide the menu if the user clicks on the document, but stop event bubbling if the event target is the container. 如果用户单击文档,则隐藏菜单,但如果事件目标是容器,则停止事件冒泡。 Also, if the menu is clicked, show the dropdown menu. 另外,如果单击菜单,则显示下拉菜单。

var menu = document.getElementById('container'), list = document.getElementById('dropdown_menu');

document.addEventListener('click', function(){
    list.style.display = 'none'; 
});
menu.addEventListener('click', function(e){
    list.style.display = 'block';
    if(e && e.stopPropagation){ e.stopPropagation(); }
    else {
        e = window.event;
        e.cancelBubble = true;
    }
});

JSFiddle JSFiddle

document.addEventListener('mousedown', show_menu);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM