如何添加JS,当我点击黄色时,一个框会将其颜色改为黄色?

时间:2018-03-28 20:37:56

标签: javascript html



document.getElementById('two').onclick = function()
    {
        document.getElementById('box1').style.backgroundColor = '#ccc';   
    } 

body {
        font: 1.2em Verdana, sans-serif;
    }
    #menu {
        list-style-type: none;
        padding-left: 0px;
        margin-left: 0px;
    }
    #menu li {
        border: 1px solid black;
        border-radius: 1em;
        padding: 3px;
        text-align: center;
        background-color:aquamarine;
        margin-bottom: 3px;
        width: 25%;
    }
    div {
        width: 100px;
        height: 100px;
        border: 1px solid black;
        font-size: 1.5em;
    }

<h2 id="firstHeading">What can we code in JavaScript?</h2>

<p> Some possible changes ... </p>
<ul id="menu">
    <li id="one"> Yellow </li>
    <li id="two"> Grey  </li>
    <li id="three"> Wide border</li>
</ul>

<div id="box1"> One </div>
<div id="box2"> Two </div>

<p><button id="reset"> Reset </button></p>
&#13;
&#13;
&#13;

我想添加JS,当我点击&#34;黄色&#34;时,第一个框的背景设置为黄色,当我点击&#34; Gray&#34;两个方框的背景颜色是#CCC,当我将鼠标移到&#34;宽边框&#34;第二个盒子的边框为10px红色,当我将鼠标移开时,#34; Wide Border&#34;返回原始的黑色&#34;。最后,当我点击重置时,一切都恢复正常。

Copy of the webpage

1 个答案:

答案 0 :(得分:0)

您的javascript代码可能如下所示。

var btn1 = document.querySelector('#one');
var btn2 = document.querySelector('#two');
var btn3 = document.querySelector('#three');
var btn4 = document.querySelector('#reset');
var box1 = document.querySelector('#box1');
var box2 = document.querySelector('#box2');
var initialBorder = box2.style.border;

btn1.addEventListener('click', function() {
    box1.style.background = 'yellow';
});

btn2.addEventListener('click', function() {
    box1.style.background = '#ccc';
    box2.style.background = '#ccc';
});

btn3.addEventListener('mouseenter', function() {
    box2.style.border = '10px solid red';
});

btn3.addEventListener('mouseleave', function() {
    box2.style.border = initialBorder;
});

btn4.addEventListener('click', function() {
    box1.style.background = 'white';
    box2.style.background = 'white';
});