选择后更改菜单项格式

时间:2015-02-28 03:08:11

标签: jquery html css

我试图通过将不同部分的示例拼凑在一起并且显然缺少某些内容来按类别更改所选li项目的颜色。

如果不清楚我是css和jquery的菜鸟。

感谢您的光临。

HTML

<div class="menuwrapper">
<ul>
    <li><a href="#">Item 1</a>
    </li>
    <li><a href="#">Item 2</a>
    </li>
    <li><a href="#">Item 3</a>
    </li>
    <li><a href="#">Item 4</a>
    </li>
    <li><a href="#">Item 5</a>
    </li>
</ul>

CSS

/* Define the body style */
 body {
    font-family:Arial;
    font-size:12px;
}
/* Remove the margin, padding, and list style of UL and LI components */
 .menuwrapper ul, .menuwrapper ul li {
    margin:0;
    padding:0;
    list-style:none;
}
/* Apply background color and border bottom white and width to 150px */
 .menuwrapper ul li {
    background-color:#7f95db;
    border-bottom:solid 1px white;
    width:150px;
    cursor:pointer;
}
/*Apply the background hover color when user hover the mouse over of the li component */
 .menuwrapper ul li:hover {
    background-color:#6679e9;
    position:relative;
}
/* Apply the link style */
 .menuwrapper ul li a {
    padding:5px 15px;
    color:#ffffff;
    display:inline-block;
    text-decoration:none;
}
/* Apply the background select color when the li component is selected */
 .menuselected li {
    background-color:#6679e9;
    border-bottom:solid 1px white;
    width:190px;
    cursor:pointer;
}

的JScript

    var main = function () {
    $(".menuwrapper ul li").click(function () {
        $(this).addClass('menuselected'); /*this applies class but does not change style of li element */
        //$(this).css("background-color","#ffaa99"); //this works when uncommented
    })
}

$(document).ready(main);

链接到代码:jsfiddle

3 个答案:

答案 0 :(得分:1)

问题是css定义。您正在将该类添加到li元素,因此css定义.menuselected li是错误的,因为它会查找位于li元素内的.menuselected子项。

此外,您遇到css specificity问题,规则.menuwrapper ul li更具体,只有li.menuselected,因此您可以使用

.menuwrapper ul li.menuselected {
    background-color:#6679e9;
    border-bottom:solid 1px white;
    width:190px;
    cursor:pointer;
}

演示:Fiddle

答案 1 :(得分:0)

您的.menuselected正在应用于li,而不是ul。

您的CSS目标应为.menuwrapper ul li.menuselected


您还可以更改JS以将类添加到父ul。

$(this).parent().addClass("menuselected");

另外:您可以考虑清除.menuselected课程,然后再将其分配给点击的li。这样,你只会选择一个li。

$(".menuselected").removeClass("menuselected");
$(this).addClass("menuselected");

除非您希望能够选择多个,在这种情况下,您可能正在寻找toggleClass()

$(this).toggleClass("menuselected");

答案 2 :(得分:0)

已经涵盖了CSS定义,您应该添加li的权重,例如:

.menuwrapper li.menuselected{
    background-color:#6679e9;
    border-bottom:solid 1px white;
    width:190px;
    cursor:pointer;
}