4

我是 javascript 的新手,我需要帮助!我需要创建一个function changeColor (newColor) {}wherechangeColor是函数的名称,并且newColor是要传递给函数的唯一参数(无法更改,我只能在函数中使用单个参数)。我有一个代表不同颜色的无序列表。例如:

<li><a href="#" >black</a></li>
<li><a href="#" >blue</a></li>
<li><a href="#" >red</a></li> etc.

我需要为每个链接添加一个 onclick 事件,如下例所示:

<li><a href="#" onclick="changeColor(newColor)">black</a></li>
<li><a href="#" onclick="changeColor(newColor)">blue</a></li>
<li><a href="#" onclick="changeColor(newColor)">red</a></li>

我需要 onclick 事件来做三件事:

1)将头部的外部css样式表(id为'styleSheet')更改为与链接所代表的颜色一致的样式表(即黑色有自己的样式表,称为black.css,蓝色有自己的样式表,称为blue.css 等)如果用户单击带有文本“black”的链接,则应加载 black.css,如果用户单击“blue”的链接,则应加载 blue.css,等等。

2)以与样式表相同的方式更改页面上显示的图像(id为'selectedImg')(即每种颜色都有自己的图像。黑色有一个名为black.jpg的图像,蓝色有一个名为blue.jpg 等)。如果用户单击“黑色”链接,则应显示 black.jpg。如果用户点击链接“蓝色”,则应显示 blue.jpg 等。

3)更改显示在图像右侧的段落文本(段落的文本)(每种颜色都有与之关联的特定文本(即黑色有var black = "here is the text that goes to the right of the black picture";蓝色有一个var blue = "here is the text that goes to the right of the blue picture";等)。如果用户点击链接对于“黑色”,分配给函数()中的变量“黑色”的文本var black = "some text for black";应显示在图像的右侧,等等。

这一切都需要在不离开默认页面的情况下完成(即链接不会去任何地方,这三个事件发生在同一页面上,具体取决于您单击的链接)。

我是 javascript 的极端新手。所以如果你这么好心给我帮助,你不能给我任何先进的技术。

我可以使用的唯一 javascript“函数”是:onclick, this, childNodes, firstChild, getElementById(), getElementsByTagName(),setAttribute()和某种简单的循环或 if 语句。

就像我说的,我必须使用一个只有一个参数的函数,并且 onclick 事件必须执行上面列出的所有三个更改。无法再创建任何函数或参数。那是我唯一可以使用的。这是HTML:

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Color Theory</title>
<link id='styleSheet' href="css/base_styles.css" rel="stylesheet" type="text/css" />
<script src="events.js" type="text/javascript"></script>
</head>

<body>
<h1>Color Theory 101</h1>
<ul id="navbar">
<li><a href="#">black</a></li>
<li><a href="#">blue</a></li>
<li><a href="#">brown</a></li>
<li><a href="#">green</a></li>
<li><a href="#">orange</a></li>
<li><a href="#">pink</a></li>
<li><a href="#">purple</a></li>
<li><a href="#">red</a></li>
<li><a href="#">white</a></li>
<li><a href="#">yellow</a></li>
</ul>
<h2>Pick a Color</h2>
<img src="images/color_theory.jpg" alt="color theory" name="selectedImg" `enter code here`id="selectedImg"  />
<p id="facts">Colors hold many different meanings in different cultures. Click a link above to learn more.</p>
</body>
</html>

非常感激任何的帮助。我知道如何分别做这三件事,但我不知道如何用同一个函数只使用一个参数同时做这三件事。

* 编辑当前代码* HTML:

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Color Theory</title>
<link id='styleSheet' href="css/base_styles.css" rel="stylesheet" type="text/css" />
<script src="events.js" type="text/javascript"></script>
</head>

<body>
<h1>Color Theory 101</h1>

<ul id="navbar">
  <li><a href="black" onclick="changeColor(this)">black</a></li>
  <li><a href="blue" onclick="changeColor(this)">blue</a></li>
  <li><a href="brown" onclick="changeColor(this)">brown</a></li>
  <li><a href="green" onclick="changeColor(this)">green</a></li>
  <li><a href="orange" onclick="changeColor(this)">orange</a></li>
  <li><a href="pink" onclick="changeColor(this)">pink</a></li>
  <li><a href="purple" onclick="changeColor(this)">purple</a></li>
  <li><a href="red" onclick="changeColor(this)">red</a></li>
  <li><a href="white" onclick="changeColor(this)">white</a></li>
  <li><a href="yellow" onclick="changeColor(this)">yellow</a></li>
</ul>
<h2>Pick a Color</h2>
<img src="images/color_theory.jpg" alt="color theory" name="selectedImg" id="selectedImg"  />
<p id="facts">Colors hold many different meanings in different cultures. Click a link above to learn more.</p>
</body>
</html>

JAVASCRIPT:

function changeColor(newColor) {

    var alertTest = newColor.getAttribute('href');
    var styleSheet = document.getElementById('styleSheet');
    var newStyle = styleSheet.setAttribute('href', newColor + '.css');
    var selectedImg = document.getElementById('selectedImg');
    var newImage = selectedImg.setAttribute('src', newColor + '.jpg');

    var black = "Black absorbs all light in the color spectrum. It is often used as a symbol of menace or evil, but it is also popular as an indicator of power. It is used to represent treacherous characters such as Dracula and is often associated with witchcraft. Black is associated with death and mourning in many cultures. It is also associated with unhappiness, sexuality, formality, and sophistication. In ancient Egypt, black represented life and rebirth. Consider how black is used in language: Black Death, blackout, black cat, black list, black market, black tie, black belt.";

    var white = "White represents purity or innocence. It is bright and can create a sense of space or add highlights. White is also described as cold, bland, and sterile. Rooms painted completely white can seem spacious, but empty and unfriendly. Hospitals and hospital workers use white to create a sense of sterility.";

    var red = "Red is a bright, warm color that evokes strong emotions. It is associated with love, warmth, and comfort. Red is also considered an intense, or even angry, color that creates feelings of excitement or intensity. Consider how red is used in language: redneck, red-hot, red-handed, paint the town red, seeing red.";

    var blue = "Blue is described as a favorite color by many people and is the color most preferred by men. It calls to mind feelings of calmness or serenity. It is often described as peaceful, tranquil, secure, and orderly. Blue can also create feelings of sadness or aloofness. It is often used to decorate offices because research has shown that people are more productive in blue rooms. Blue is one of the most popular colors, but it is one of the least appetizing. Some weight loss plans even recommend eating your food off of a blue plate. Blue rarely occurs naturally in food aside from blueberries and some plums. Also, humans are geared to avoid foods that are poisonous and blue coloring in food is often a sign of spoilage or poison. Blue can also lower the pulse rate and body temperature. Consider how blue is used in language: blue moon, blue Monday, blue blood, the blues, and blue ribbon.";

    var green = "Green is a cool color that symbolizes nature and the natural world. It also represents tranquility, good luck, health, and jealousy. Researchers have also found that green can improve reading ability. Some students may find that laying a transparent sheet of green paper over reading material increases reading speed and comprehension. Green has long been a symbol of fertility and was once the preferred color choice for wedding gowns in the 15th-century. Even today, green M & M's (an American chocolate candy) are said to send a sexual message. Green is often used in decorating for its calming effect. For example, guests waiting to appear on television programs often wait in a 'green room' to relax. Green is thought to relieve stress and help heal. Those who have a green work environment experience fewer stomachaches. Consider how green is used in language: green thumb, green with envy, greenhorn.";

    var yellow = "Yellow is a bright that is often described as cheery and warm. It is also the most fatiguing to the eye due to the high amount of light that is reflected. Using yellow as a background on paper or computer monitors can lead to eyestrain or vision loss in extreme cases. Yellow can also create feelings of frustration and anger. While it is considered a cheerful color, people are more likely to lose their tempers in yellow rooms and babies tend to cry more in yellow rooms. Yellow can also increase the metabolism. Since yellow is the most visible color, it is also the most attention-getting color. Yellow can be used in small amount to draw notice, such as on traffic sign or advertisements.";

    var purple = "Purple is the symbol of royalty and wealth. Purple also represents wisdom and spirituality. Purple does not often occur in nature, it can sometimes appear exotic or artificial.";

    var brown = "Brown is a natural color that evokes a sense of strength and reliability. It can also create feelings of sadness and isolation. Brown brings to mind feeling of warmth, comfort, and security. It is often described as natural, down-to-earth, and conventional, but brown can also be sophisticated.";

    var orange = "range is a combination of yellow and red and is considered an energetic color. Orange calls to mind feelings of excitement, enthusiasm, and warmth. Orange is often used to draw attention, such as in traffic signs and advertising.";

    var pink = "Pink is essentially a light red and is usually associated with love and romance. It is thought to have a calming effect. One shade known as 'drunk-tank pink' is sometimes used in prisons to calm inmates. Sports teams sometimes paint the opposing teams locker room pink to keep the players passive and less energetic. While pink's calming effect has been demonstrated, researchers of color psychology have found that this effect only occurs during the initial exposure to the color. When used in prisons, inmates often become even more agitated once they become accustomed to the color.";

    if (newColor === 'black') {
        factsText = black;
    } else if (newColor === 'blue') {
        factsText = blue;
    } else if (newColor === 'brown') {
        factsText = brown;
    } else if (newColor == 'green') {
        factsText = green;
    } else if (newColor === 'orange') {
        factsText = orange;
    } else if (newColor === 'pink') {
        factsText = pink;
    } else if (newColor === 'purple') {
        factsText = purple;
    } else if (newColor === 'red') {
        factsText = red;
    } else if (newColor === 'white') {
        factsText = white;
    } else {
        factsText = yellow;
    }
}
4

1 回答 1

1

我会做这样的事情

<li><a href="#" onclick="changeColor(this.childNodes[0].nodeValue)">blue</a></li>
<li><a href="#" onclick="changeColor(this.childNodes[0].nodeValue)">black</a></li>
<li><a href="#" onclick="changeColor(this.childNodes[0].nodeValue)">yellow</a></li>
<li><a href="#" onclick="changeColor(this.childNodes[0].nodeValue)">green</a></li>

ETC...

和 javascript

var black = "here is the text that goes to the right of the black picture"; 
var blue = "here is the text that goes to the right of the blue"; 
//etc
function changeColor(color)
{

    document.getElementById('styleSheet').setAttribute('href', color + '.css');
    document.getElementById('selectedImg').setAttribute('src', color + '.jpg');
    document.getElementById('facts').innerHTML = window[color];

}

编辑

根据评论对 javascript 稍作修改

function changeColor(color)
    {
        var black = "here is the text that goes to the right of the black picture"; 
        var blue = "here is the text that goes to the right of the blue"; 
        //etc

        var textToShowInParagraph;
        document.getElementById('styleSheet').setAttribute('href', color + '.css');
        document.getElementById('selectedImg').setAttribute('src', color + '.jpg');

        if (color === 'black')
        {
             textToShowInParagraph = black;
        }
        else if (color === 'blue')
        {
              textToShowInParagraph = blue;
        } else if //con....

        document.getElementById('facts').childNodes[0].nodeValue = textToShowInParagraph;

    }

或使用 switch 语句

 function changeColor(color)
        {
            var black = "here is the text that goes to the right of the black picture"; 
            var blue = "here is the text that goes to the right of the blue"; 
            //etc

            var textToShowInParagraph;
            document.getElementById('styleSheet').setAttribute('href', color + '.css');
            document.getElementById('selectedImg').setAttribute('src', color + '.jpg');

            switch (color) {
                case "black":
                    textToShowInParagraph = black;
                    break;
                case "blue":
                    textToShowInParagraph = blue;
                    break;
                //con..
                default:
                    break;
             }

            document.getElementById('facts').childNodes[0].nodeValue = textToShowInParagraph;

        }

或者您可以使用一些局部对象变量范围来做与第一个类似的事情,其中​​变量是包含函数的属性而不是窗口(但这可能对您来说太远了,基于您非常奇怪的限制 -没有把握??)

例如

function changeColor(color)
{
    this.black = "here is the text that goes to the right of the black picture"; 
    this.blue = "here is the text that goes to the right of the blue"; 
    //etc       

    document.getElementById('styleSheet').setAttribute('href', color + '.css');
    document.getElementById('selectedImg').setAttribute('src', color + '.jpg');
    document.getElementById('facts').childNodes[0].nodeValue = this[color];
 }

根据问题编辑当前代码编辑

首先,我不会将颜色值存储在 a 标签的 href 中。浏览器希望找到一个有效的 url,或在那里找到一个锚点(即http://somewhere.com或 #footer)。放# 是OKish,这将导致一个空的锚导航(即点击不会去任何地方)。因此,首先将 a 标签更改为以下内容。

<a href="#" onclick="changeColor(this)">yellow</a>

接下来是在 javascript 函数中,我会更改为更像这样:

function changeColor(callingATag) {

    //get the newColor from the calling a tags child text node
    var newColor = callingATag.childNodes[0].nodeValue;

    //set the stylesheet href
    document.getElementById('styleSheet').setAttribute('href', newColor + '.css');
    // No need to set variables, can do it in one line, and the return value from 
    // setAttribute is undefined anyway

    // Set the img src attribute
    document.getElementById('selectedImg').setAttribute('src', newColor + '.jpg');
    //Same as above

    //Color text description variables fine
    var black = //etc.. etc.. con...

    //Color test to set text - fine but NOTE you had not declared the 
    // factsText variable, and in you code you don't do 
    // anything with it afterwards
    var factsText;
    if (newColor === 'black') {
        factsText = black;
    //etc.. etc..

    //then set the facts element text
    document.getElementById('facts').childNodes[0].nodeValue = factsText;

}

有几点需要注意。如果您对 setAttribute 的任何调用失败,则该函数的其余部分很可能会失败。此外,如果元素中没有文本,您将没有 .childNode[0].nodeValue,您将不得不使用 appendChild 来创建子节点。

另一个说明,我想向您介绍jsFiddle,一个Web开发人员小沙箱,实验工具,http://jsfiddle.net

为了进一步详细说明,我为您做了一个小提琴,在 chrome 和 firefox 中进行了测试并且工作正常。不完全是您需要的代码,但是(即没有任何样式表或图像要更改)但原理是相同的。下方链接:

http://jsfiddle.net/4chVw/5/

于 2012-09-21T02:43:27.283 回答