我的问题是<a> not changing on toggleClass()

时间:2017-07-13 11:52:52

标签: javascript jquery css fonts

I am creating a html website which has a menu on top that is supposed to have a transparent background, and the menu items should have black font color, when on top of the scroll view and fade to a red background, with white font color, when the user scrolls down. For the purpose of that i have written this function in my javascript file main.js:

window.onscroll = function () {
    if (window.scrollY === 1 || window.scrollY === 0) {
        $(".menu").toggleClass("scroll");
        $(".menu a, li").toggleClass("fontScroll");
    }
};

fontScroll is a function in my CSS that changes the font color of my menu items from the original color, black, to a white color, and the function for that is like this:

.fontScroll {
    color: rgb(250,250,245);
}

I have three list items in my menu, a title and two links, and for some weird reason the title is the only thing that becomes white and the links stay the same color. Am I doing something wrong?

Oh, and by the way, I have tried setting a:visited and a:link and that didn't work.

If you are interested i have created a codepen的字体颜色。

提前致谢:)

1 个答案:

答案 0 :(得分:1)

您可以使用解决方案https://codepen.io/Shiladitya/pen/jwdzxq

/*jslint browser: true*/
/*global $, jQuery, alert*/

function main() {
    "use strict";
    window.onscroll = function () {
      if (window.scrollY === 1 ||                   window.scrollY === 0) {
        $(".menu").toggleClass("scroll");
        $(".menu a, li").toggleClass("fontScroll");
    }
  };
}

$(document).ready(main);
.font {
	color: rgb(50, 50, 50);
	text-decoration: none;
}

.menu a:hover {
	color: rgb(100, 100, 100);
}

.menu {
	overflow: hidden;
	position: fixed;
	background-color: rgba(179, 0, 0, 0);
	height: auto;
    top: 0;
    left: 0;
    right: 0;
	z-index: 100;
    transition: all 0.4s;
}

.menu #title {
	font-size: 35px;
}

.menu #home {
    margin-right: 6%;
    margin-left: 12%;
}

.menu #about {
    margin-right:0;
}

.menu li {
	display: inline-block;
    transition: all 0.4s;
}

.spaceForScroll {
    width: 100%;
    height: 1500px;
}

.scroll {
    background-color: rgba(179, 0, 0, 0.8);
    transition: all 0.4s;
}

.fontScroll {
    color: rgb(250,250,245);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
	<head>
		<link href="style.css" type="text/css" rel="stylesheet">
     <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="main.js"></script>
	</head>

	<body>
		<nav class="menu"> 
			<ul id="titles">
				<li id="title">Title</li>
				<li id="home"><a class="font" href="index.en.html">Home</a></li>
				<li id="about"><a class="font" href="about.en.html">About</a></li>
			</ul>
    </nav>
    <div class="spaceForScroll"></div>
  </body>
</html>

而不是定位我使用过类的元素。