简体   繁体   中英

Change css font-weight upon click

I am pretty new to css + html and am coding my first website. I have a navigation menu setup inside a div, but I want to change the font-weight of the clicked text from lighter to bold when the user clicks on an item in it (text). Please can you tell me how to do this?

Here is my code so far:

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <title>...</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz" />
</head>
<body>
    <div id="background" />
        <div id="navigation" class="navigationPlaceholder">
            <div id="navigationText">
                <ul>
                    iOS
                    Blog
                    About
                    Contact
                </ul>
            </div>
        </div>
   </body>
</html>

here you have an example, you should do the same wih your div:

<html>
 <head>
  <script type="text/javascript">
   function displayResult()
   {
   document.getElementById("p1").style.fontWeight="900";
   }
  </script>
 </head>
 <body>
  <p id="p1">This is some text.</p>
  <br />
  <button type="button" onclick="displayResult()">Change font weight</button>
 </body>
</html>

You need to add a click event listener each navigation item and change its font-weight style.

First, start by using an unordered list for your nav

<div id="navigationText">
    <ul>
        <li>iOS</li>
        <li>Blog</li>
        <li>About</li>
        <li>Contact</li>
    </ul>
</div>

Then, place this script block just before the closing </body> tag

<script type="text/javascript">
var nav = document.getElementById('navigationText');

var navItems = nav.getElementsByTagName('li');

for (var i = 0; i < navItems.length; i++) {
    navItems[i].addEventListener('click', function() {
        this.style.fontWeight = 'bold';
    }, false);
}
</script>
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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