onClick change list styles

前端 未结 3 1480
走了就别回头了
走了就别回头了 2021-01-22 02:52

Let\'s say I have a simple list:

  
  • 1
  • 2
相关标签:
3条回答
  • 2021-01-22 03:30
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
        <head>
            <title></title>
            <script language="JavaScript" type="text/javascript">
                /*<![CDATA[*/
                var Lst;
    
                function CngClass(obj){
                 if (Lst) Lst.className='';
                 obj.className='Clicked';
                 Lst=obj;
                }
    
                /*]]>*/
            </script>
            <style>
                .notClicked {color: black}
                .Clicked {color: red}
            </style>
        </head>
    
        <body>
            <ul>
                <li>
                    <a onclick="CngClass(this);" href="#" class="notClicked">1
                    </a>
                </li>
                <li>
                    <a onclick="CngClass(this);" href="#"  class="notClicked">2
                    </a>
                </li>
                <li>
                    <a onclick="CngClass(this);" href="#"  class="notClicked">3
                    </a>
                </li>
            </ul>
        </body>
    </html>
    
    0 讨论(0)
  • 2021-01-22 03:30

    Why change the style of the other? You may want to change the style of the clicked element.

    If so, you can use jQuery for that

    Example:

    <li class = "notClicked">element 1</li>
    <li class = "notClicked">element 2</li>
    <li class = "notClicked">element 3</li>
    
    $('.notClicked').click(function()
    {
        $(this).addClass('active');
    });
    
    0 讨论(0)
  • 2021-01-22 03:40
    <script>
        function changeClass(){
            document.getElementById("idElement").setAttribute("class", "Clicked");
        }
    </script>
    
    <ul>
        <li class="notClicked" >1</li>
        <li class="notClicked" onClick="changeClass()" id="idElement">2</li>
        <li class="notClicked">3</li>
    </ul>
    
    0 讨论(0)
提交回复
热议问题