单击按钮即可更改网站链接的颜色

时间:2018-06-25 10:14:08

标签: javascript button

我创建了一个线性渐变并用javascript对其进行了动画处理,并将其设置为我的网站的背景。然后,我在HTML中添加了一个按钮,当单击渐变的颜色时,该按钮会关闭。

现在,我试图使按钮也更改页面上文本链接的颜色,但似乎无法弄清楚。有人可以让我知道我哪里出错了吗?谢谢。

Java脚本

var angle = 0, color = "#666", colors = "#000", font = "rgba(102, 102, 102, .3)";
var changeBackground = function() {
  angle = angle + .4
  document.body.style.backgroundImage = "linear-gradient(" + angle + 
"deg, " + colors + ", " + color + ", " + colors + ",  " + color + ",  " 
+ colors + ",  " + color + ", " + colors + ",  " + color + ", " + colors 
+ ",  " + color + ", " + colors + ", " + color;
  requestAnimationFrame(changeBackground)
}

var changeFont = function() {
  document.a.style.color = "color(" + font;
}

changeBackground()

document.querySelector('#myBtn').addEventListener('click', function () {
  color = (color != "#666") ? "#666" : "#fff";
  colors = (colors != "#000") ? "#000" : "#6839ba";
  font = (font != "rgba(102, 102, 102, .3)") ? "rgba(102, 102, 102, .3)" 
: "rgba(247, 201, 180, .3)";
})

HTML按钮和链接

<main class="main">
    <button class="Btn" id="myBtn">Click</button>
    <ul class="position">
        <li class="fnup"><a href="#">fn-up   </a></li>
        <li class="about"><a href="#">about   </a></li>
        <li class="issue hover"><a href="#">issue 0 </a></li>
        <li class="contact hover"><a href="#">contact</a></li>
    </ul>
</main>

1 个答案:

答案 0 :(得分:1)

点击按钮时,您需要致电changeFont。您还需要changeFont遍历所有a并设置其style.color属性。

虽然您可以做到这一点,但由于颜色太相似,因此IMO难以理解:

var angle = 0, color = "#666", colors = "#000", font = "rgba(102, 102, 102, .3)";
var changeBackground = function() {
  angle = angle + .4
  document.body.style.backgroundImage = "linear-gradient(" + angle + 
"deg, " + colors + ", " + color + ", " + colors + ",  " + color + ",  " 
+ colors + ",  " + color + ", " + colors + ",  " + color + ", " + colors 
+ ",  " + color + ", " + colors + ", " + color;
  requestAnimationFrame(changeBackground)
}

var changeFont = function() {
  document.querySelectorAll('a').forEach(a => a.style.color = font);
}

changeBackground();
changeFont();

document.querySelector('#myBtn').addEventListener('click', function () {
  color = (color != "#666") ? "#666" : "#fff";
  colors = (colors != "#000") ? "#000" : "#6839ba";
  font = (font != "rgba(102, 102, 102, .3)") ? "rgba(102, 102, 102, .3)" 
: "rgba(247, 201, 180, .3)";
  changeFont();
})
<main class="main">
  <button class="Btn" id="myBtn">Click</button>
  <ul class="position">
    <li class="fnup"><a href="#">fn-up   </a></li>
    <li class="about"><a href="#">about   </a></li>
    <li class="issue hover"><a href="#">issue 0 </a></li>
    <li class="contact hover"><a href="#">contact</a></li>
</main>