【问题标题】:changing background color when clicking button单击按钮时更改背景颜色
【发布时间】:2017-08-02 22:52:01
【问题描述】:

我是编码新手,我正在做一些小事。当我点击这个按钮时,我试图让页面的背景发生变化。由于我是编码新手,因此我不知道使用此方法的正确方法。任何建议都会有所帮助。到目前为止,这是我在 html 和 css 中所拥有的。

<div class="wrapper>
<p>Click on the button to see the magic happen!</p>
<input class="button" type="button" value="Click Me">

然后在 CSS 中我有以下内容:

.wrapper{
text-align: center;
}
.button{
display: inline-block;
padding: 15px 25px;
font-size: 24px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #EE835A;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
}
.button:hover {background-color: #EE8354A}

.button:active {
background-color: #4A6273;
box-shadow: 0 5px #F68B8B;
transform: translateY(4px);
}

【问题讨论】:

标签: javascript html button


【解决方案1】:

花点时间做了,你有几处不对,看看看看。这也是一个纯 CSS 的解决方案。

悬停颜色中的字符过多。应该是 6 而不是 7。我把它换成了黑色 #000000,因为我不确定你想要什么颜色。

此外,添加微妙的过渡效果很好。

transition: .3s

.button:hover {background-color: #000000; transition: .3s}

body {background-color: white;}

.button:active {
background-color: #4A6273;
box-shadow: 0 5px #F68B8B;
transform: translateY(4px);
}

.wrapper{
text-align: center;
}
.button{
display: inline-block;
padding: 15px 25px;
font-size: 24px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #EE835A;
border: none;
border-radius: 15px;
box-shadow: 0 9px #999;
transition: .3s;
}
<div class="wrapper">
<p>Click on the button to see the magic happen!</p>
<button class="button" onclick="document.body.style.backgroundColor = 'green';"></button>

【讨论】:

    【解决方案2】:

    一个简单的 JQuery 脚本就可以完成这个:

    $('.button').click(function(e){
        e.preventDefault();
        $('body').css({'background':'red'});
    });
    

    https://jsfiddle.net/f1rkyxs7/2/

    【讨论】:

    • OP 要求 js、css 或 html 而不是 jquery。
    • @norcaljohnny JQuery 几乎是 javascript 的代名词。新手可能会发现更容易开始。除非他们明确说没有 JQuery,否则我认为教它没有错。
    • 我同意 jquery 是一个很好的功能并且更喜欢它,但是像颜色更改这样简单的事情可以在 CSS 中完成,而无需加载额外的脚本。但我同意。
    猜你喜欢
    • 2014-10-09
    • 2014-10-10
    • 1970-01-01
    • 2019-04-14
    • 2014-10-07
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多