简体   繁体   English

使用javascript / jQuery更改类的background-color属性

[英]Changing background-color property of a class with javascript/jQuery

This seems like a simple problem but nothing nothing is fixing it. 这似乎是一个简单的问题,但没有什么能解决它。 I'm trying to dynamically change the background-color (from white or pink to green) on some text with javascript/jQuery but for some reason it's not working. 我试图用javascript / jQuery动态地改变某些文本的背景颜色(从白色或粉红色到绿色),但由于某种原因它不起作用。 The text is styled with a CSS class called ".novice". 该文本使用名为“.novice”的CSS类进行样式设置。

Here's the CSS. 这是CSS。 It's simple. 这很简单。 I've also tried removing background-color completely so it does not already have a set background-color. 我也尝试完全删除背景颜色,因此它还没有设置背景颜色。

<style type="text/css">
.novice {
background-color: pink;
}

</style>

Here is an array with items I wrote out using a loop. 这是一个数组,其中包含我使用循环写出的项目。 The first item has the class "novice" 第一项有“新手”类

var achievements = ['<span class="novice">novice - 10 or more guesses </span>', ...]

Below is an if statement, which if true, is supposed to make the ".novice" class have a "background-color: green" property and make "novice - 10 or more guesses" be highlighted in green. 下面是一个if语句,如果为true,则应该使“.novice”类具有“background-color:green”属性,并使“新手 - 10个或更多猜测”以绿色突出显示。 I'm positive that I have the variable timesguessed set up correctly and spelled right. 我很肯定我已经正确设置了变量timeguessed并拼写正确。 However when timesguessed is greater than 10, "novice..." will still not be highlighted in green. 但是,当时间推测大于10时,“新手......”仍然不会以绿色突出显示。

if (timesguessed > 10) {
    $('.novice').css('background-color', 'green'); 
}

Am I typing this above portion right? 我输入上面这部分了吗? I've also tried replacing $('.novice').css('background-color', 'green'); 我也试过替换$('。novice')。css('background-color','green'); with $('.novice').background-color(green); with $('。novice')。background-color(green); , though that's probably wrong. 虽然这可能是错的。

Even if I print out another line with the supposedly newly modified "novice" class the text will still not be highlighted in green. 即使我用所谓的新修改的“新手”类打印出另一行,文本仍然不会以绿色突出显示。

document.write('<span class="novice">novice - 10 or more guesses </span>'); 

I know that the original CSS .novice class is working because the text will be highlighted in pink if no matter if timesguessed is greater or less than 10. 我知道原来的CSS .novice类正在工作,因为如果时间间隔大于或小于10,文本将以粉红色突出显示。

I'm not sure if the Javascript is not modifying the CSS class, or what. 我不确定Javascript是不是在修改CSS类,或者是什么。 Or maybe it does just something else is overriding it? 或者它可能只是其他东西覆盖它?

Thanks for the help. 谢谢您的帮助。 Yeah I'm a beginner at javascript/jQuery. 是的我是javascript / jQuery的初学者。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.novice {
}

</style>
<script type="text/javascript" src="../MM_JAVASCRIPT2E/MM_JAVASCRIPT2E/_js/jquery-1.6.3.min.js"></script>

<title>Number Guessing Game</title>


</head>

    <body>
    <h1 style="text-align:center;"> Number Game </br> Try to guess my number that is between 0-1000 </h1>
    <script>
// BEGIN LONG BLOCK OF CODE WITH GUESSING GAME MECHANISMS. You can ignore this part I think, this part works.
    var realnumber = prompt('Player 1, please enter a number for Player 2 to guess then hand it off to Player 2.', '');
    while (isNaN(realnumber)) {
        realnumber = prompt('Player 1, please enter a NUMBER, dimwit, for Player 2 to guess.', '');}
    var timesguessed=0;
    while (numbertoguess != 0) {
    var numbertoguess = prompt("Player 2, guess a number", "");
    while (isNaN(numbertoguess)) {
        numbertoguess = prompt('Please, type in a number');} // why don't I need an "else" here?
    numbertoguess = Math.abs(numbertoguess - realnumber);
        if ( numbertoguess >= 50 ) {
        alert("Tundra cold");
        timesguessed++;
        }
    else if ( 30 <= numbertoguess && numbertoguess < 50) {
        alert("cold");
        timesguessed++;
        }
    else if ( 20 <= numbertoguess && numbertoguess < 30 ) {
        alert("warm");
        timesguessed++;
        }
    else if ( 10 <= numbertoguess && numbertoguess< 20 ) {
        alert("hot");
        timesguessed++;
    }
    else if ( 5 <= numbertoguess && numbertoguess < 10 ) {
        alert("Steaming hot!");
        timesguessed++;
        }
    else if ( 3 <= numbertoguess && numbertoguess < 5 ) {
        alert("SCALDING HOT!");
        timesguessed++;
    }
    else if ( 1 < numbertoguess && numbertoguess < 3 ) {
        alert("FIRE!");
        timesguessed++;
    }
    else if ( numbertoguess == 1 ) {
        alert("Face Melting!");
        timesguessed++;
    } else if ( numbertoguess == 0 ) { 
        alert("BINGO!");
        timesguessed++;
    }
    }
    document.write('</br></br></br></br><h2 style="text-align:center; font-size: 18px;"> The number was ' + realnumber + '.');
    if (timesguessed == 1) {
        document.write('</span><h2 style="text-align:center;">It took you ' + timesguessed + ' guess.</h2>');
    } else {
    document.write('<h2 style="text-align:center;">It took you ' + timesguessed + ' guesses.</h2>');
    }

// END LONG BLOCK OF CODE WITH GUESSING GAME MECHANISMS


    document.write('</br></br>')
//below is the array written out with a loop
    var achievements = ['<span class="novice">novice - 10 or more guesses </span>',bronze - 7-10 guesses', 'silver', 'gold', 'titanium', 'platinum', 'diamond', ]
    var counter = 0;
        while (counter < achievements.length) {
        document.write('<h2 style="text-align:center;">' + achievements[counter] + ' ');
        counter++;
        }
//below is the "if" function of question
    if (timesguessed > 10) {
        $('.novice').css('background-color', '#00FF00'); //why does this not work?
    }
    document.write('<span class="novice">novice - 10 or more guesses </span>'); //why does this not work?

    </script>

    </body>
    </html>

.css() in your code changes the style of elements that are already on the page by adding inline styles to them - not by modifying the css rule. 代码中的.css()通过向其添加内联样式来更改页面上已有元素的样式 - 而不是通过修改css规则。

You can add a new rule at runtime like so: 您可以在运行时添加新规则,如下所示:

$('head').append('<style type="text/css">.novice{color:green;}</style>'); 

I am not a proponent of such modifications though. 我不是这种修改的支持者。 I'd much rather see css like 我更喜欢看css

.novice {background-color: pink;}
.over-ten-guesses .novice {background-color:green;}

After that you can toggle the .over-ten-guesses class with Javascript on any container element that has .novice as its descendant. 之后,您可以在任何以.novice作为其后代的容器元素上使用Javascript切换.over-ten-guesses .novice

You can do it in following ways STEP 1 您可以通过以下方式执行步骤1

   var imageUrl= "URL OF THE IMAGE HERE";
   var BackgroundColor="RED"; // what ever color you want

for elements with same class 对于具有相同类的元素

var elements = document.getElementsByClassName("ClassName")
            for (var i = 0; i < elements.length; i++) {
                elements[i].style.background=imageUrl; 
                //if you want to change bg image
                //if you want to change bg color
                elements[i].style.backgroundColor=BackgroundColor ;
            }

To change an element with ID 要更改带ID的元素

document.getElementById("ElementId").style.backgroundImage=imageUrl
document.getElementById("ElementId").style.backgroundColor=BackgroundColor 

jQuery is not being included in the page correctly. jQuery未正确包含在页面中。 Checking your console will tell you if the link failed (and should also say that $ is undefined). 检查控制台将告诉您链接是否失败(并且还应该说$未定义)。 To use the latest version from google use this link: http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js 要使用谷歌的最新版本,请使用以下链接: http//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js

ie Change this: 即改变这个:

<script type="text/javascript" src="../MM_JAVASCRIPT2E/MM_JAVASCRIPT2E/_js/jquery-1.6.3.min.js"></script>

to this 对此

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>

Calling a method on an undefined object would cause an error, and execution of subsequent code will fail. 在未定义的对象上调用方法会导致错误,并且后续代码的执行将失败。

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

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