4

私はJavaScriptの完全な初心者であり、助けが必要です!関数の名前であり、関数に渡される唯一の引数であるfunction changeColor (newColor) {}whereを作成する必要があります(これを変更することはできません。関数で使用できる引数は1つだけです)。さまざまな色を表す順序付けられていないリストがあります。例えば:changeColornewColor

<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>

次の3つのことを行うには、onclickイベントが必要です。

1)ヘッドセクションの外部cssスタイルシート(IDは「styleSheet」)を、リンクが表す色に合わせたスタイルシートに変更します(つまり、黒にはblack.cssという独自のスタイルシートがあり、青にはという独自のスタイルシートがあります) blue.cssなど)ユーザーが「black」というテキストのリンクをクリックすると、black.cssが読み込まれ、「blue」のリンクをクリックすると、blue.cssが読み込まれます。

2)スタイルシートと同じ方法で(「selectedImg」のIDで)ページに表示される画像を変更します(つまり、各色には独自の画像があります。黒にはblack.jpgという画像があり、青には「black.jpg」という画像があります。 blue.jpgなど)。ユーザーが「黒」のリンクをクリックすると、black.jpgが表示されます。ユーザーがリンク「blue」をクリックすると、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";画像の右側に表示する必要があります。

これはすべて、デフォルトページを離れずに実行する必要があります(つまり、リンクはどこにも移動せず、クリックしたリンクに応じて3つのイベントが同じページで発生します)。

私はjavascriptの非常に初心者です。ですから、もしあなたが私にこれを手伝ってくれて親切なら、あなたは私に高度な技術を与えることはできません。

私が使用できる唯一のjavascript「関数」は、、、、、、、、、およびある種の単純なループまたはifonclickステートメントです。thischildNodesfirstChildgetElementById()getElementsByTagName()setAttribute()

私が言ったように、引数が1つしかない関数を使用する必要があり、onclickイベントは上記の3つの変更すべてを実行する必要があります。これ以上関数または引数を作成できません。私が使えるのはそれだけです。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>

どんな助けでも大歓迎です。私は3つのことすべてを別々に行う方法を知っていますが、1つの引数だけを使用して、同じ関数でそれらすべてを同時に行う方法を理解することはできません。

*現在のコードを編集* 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>

等...

そしてジャバスクリプト

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) を見つけることを期待しています。# を付けても問題ありません。これにより、空のアンカー ナビゲーションが発生します (つまり、クリックしてもどこにも移動しません)。したがって、最初のポイントは 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 を使用して子ノードを作成する必要があります。

別のメモとして、Web 開発者向けの小さなサンドボックス、実験ツールである jsFiddle を紹介したいと思います ( http://jsfiddle.net )。

さらに詳しく説明するために、私はあなたのためにフィドルを行い、クロムとファイアフォックスでテストし、正常に動作しました. 必要なコードとはまったく異なりますが (つまり、変更するスタイルシートや画像がありませんでした)、原則は同じです。以下のリンク:

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

于 2012-09-21T02:43:27.283 に答える