问题描述:

I have a webpage that has a link set to change the background colour of the page, the colour of the link, & the link text. Here is my code:

<html>

<head>

<title>Title</title>

<script type="text/javascript">

function Lights() {

document.body.style.backgroundColor='#000000';

document.getElementById("on").innerHTML="Turn on the lights";

document.getElementById("on").style.color="#00ffff";

}

</script>

</head>

<body style="font-size:200px; text-align:center;">

<a href="javascript:void(0)" id="on" onclick="Lights()">Turn off the lights</a>

</body>

</html>

I was wondering how I would set the JavaScript to reverse those statements when the link is clicked again so the page is back to the white background, the text is back to "Turn off the lights", & the link is back to the darker blue.

Thank you

网友答案:

You can use a variable to store the state and toggle based off that.

<script type="text/javascript">
  var toggle = false;
  function Lights() {
    var link = document.getElementById("on");
    document.body.style.backgroundColor= toggle ? '#ffffff' : '#000000';
    link.innerHTML=toggle ? "Turn off the lights": "Turn on the lights";
    link.style.color= toggle ? '#000000': "#00ffff";
    toggle = !toggle;
  }
</script>
网友答案:

You can toggle the settings based on a class value:

<a ... class="lightsOn" onclick="Lights(this);" ...>Turn off the lights</a>

then:

function lights(element) {
    if (element.className == 'lightsOn') {
        element.className = 'lightsOff';
        // do settings for lights off
    } else {
        element.className = 'lightsOn';
        // do settings for lights on
    }
}

Most of the setting can be assigned to the class in CSS rather than hard coded in the function.

Note that function names starting with a capital letter are, by convention, reserved for constructors, and you shouldn't use an A element if you don't want an A, use a span with appropriate styling:

<style type="text/css">
  .clickable {
    cursor: pointer;
    text-decoration: underline;
    font-color: blue;
  }
</style>

<span class="clickable" ...> ... </span>
相关阅读:
Top