如何使用JavaScript在菜单项的单击事件上设置菜单 [英] how to set menus on click event of menu item with help of javascript

查看:66
本文介绍了如何使用JavaScript在菜单项的单击事件上设置菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个菜单,我想要的是,当我单击菜单的父项时,只有子项目应该显示,意味着我不想在javascript的帮助下在鼠标悬停时显示子项目.我该怎么办.我应该设置任何属性还是必须为其编写代码,请帮忙.

i have a menu, what i want is that when i click on parent item of menu then only subitem should display,mean i dont want to display subitem on mouseover with help of javascript . what should i do.Is there any property should i set or i have to write code for it please help.

推荐答案

我会这样做的方式在每个菜单项内添加 indie 内容.您可以根据其父类决定是否显示此内容.然后,每当您单击父元素时,只需切换一个类名即可.

这是一个粗略的示例.样式很讨厌,但可以证明其目的.
另外,您不应该像我一样在html元素上真正使用内联javascript.您应该给他们提供一个类,然后为任何< li>上的点击"添加addEventListener.具有此className的元素.我会留给您的.


The way I''d go about it would be to add content indie inside each menu item. You decide whether or not to show this content based on the class of it''s parent. Then, whenever you click the parent element, you simply toggle a class name.

Here''s a rough sample. The styles are pretty nasty, but it demonstrates the purpose.
Also, you shouldn''t really use inline javascript on the html elements like I did. You should give them a class and then addEventListener for ''click'' on any <li> element that has this className. I''ll leave that as an exerise for you.


<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}

window.addEventListener('load', mInit, false);

function mInit()
{
}

function toggleClass(element, newStr)
{
    index=element.className.indexOf(newStr);
    if ( index == -1)
        element.className += ' '+newStr;
    else
    {
        if (index != 0)
            newStr = ' '+newStr;
        element.className = element.className.replace(newStr, '');
    }
}

</script>
<style>
li ul
{
    display: none;
}
li.open ul
{
    display: block;
}
</style>
</head>
<body>
    <ul>
        <li onclick='toggleClass(this, "open");'>Option 1
            <ul>
                <li>opt 1a</li>
                <li>opt 1b</li>
            </ul>
        </li>
        <li onclick='toggleClass(this, "open");'>Option 2</li>
        <li onclick='toggleClass(this, "open");'>Option 3
            <ul>
                <li>opt 1a</li>
                <li>opt 1b</li>
            </ul>
        </li>
    </ul>
</body>
</html>


这篇关于如何使用JavaScript在菜单项的单击事件上设置菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆