简体   繁体   English

为什么按钮的背景没有改变颜色?

[英]Why isn't my background for the button changing color?

I'm trying to change the color of both the body and a button when the button itself is clicked. 单击按钮本身时,我试图更改按钮主体和按钮的颜色。

Right now, the body of the page changes color randomly. 现在,页面的主体会随机更改颜色。 However this is not working for the button itself. 但是,这不适用于按钮本身。

Any ideas? 有任何想法吗?

This is my CSS for the button: 这是按钮的CSS:

#loadQuote {
  position: fixed;
  width: 12em;
  display: inline-block;
  left: 50%;
  margin-left: -6em;
  bottom: 150px;
  border-radius: 4px;
  border: 2px solid #fff;
  color: #fff;
  background-color: #36b55c;
  padding: 15px 0;
  transition: .5s ;
}
#loadQuote:hover {
  background-color: rgba(255,255,255,.25);
}
#loadQuote:focus {
  outline: none;
}

And this is my JavaScript: 这是我的JavaScript:

// prints quote
function printQuote(){

    var finalQuote = buildQuote();
    document.getElementById('quote-box').innerHTML = finalQuote;

    var color = '#'+Math.floor(Math.random()*16777215).toString(16);
    document.body.style.background = color;
    document.loadQuote.style.backgroundColor = color;
}

Thank you 谢谢

Your element selector is incorrect. 您的元素选择器不正确。 Use document.getElementById to select the element. 使用document.getElementById选择元素。

// prints quote
function printQuote(){

    var finalQuote = buildQuote();
    document.getElementById('quote-box').innerHTML = finalQuote;

    var color = '#'+Math.floor(Math.random()*16777215).toString(16);
    document.body.style.background = color;
    //BELOW LINE IS THE CHANGED CODE
    document.getElementById('loadQuote').style.backgroundColor = color;
}

You have an issue at this line: 您在此行遇到问题:

document.loadQuote.style.backgroundColor = color; ; ;

basically loadQuote is not an object in document . 基本上loadQuote不是document的对象。

Instead you need to select a DOM element using document.getElementById() like: 相反,您需要使用document.getElementById()选择一个DOM元素,例如:

document.getElementById('loadQuote'); // if you have a DOM element with ID loadQuote

Or using Document.querySelector() passing a CSS selector, just an example: 或使用传递CSS选择器的Document.querySelector()只是一个示例:

document.querySelector('.loadQuote'); // if you DOM element has .loadQuote appplied

More information on document.querySelector() can be found here: 有关document.querySelector()更多信息,可以在这里找到:

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM